首页 > 解决方案 > 我似乎无法在 python 中处理来自 regex(re.search) 的空白结果,我要么得到重复,要么没有结果?

问题描述

我正在尝试从https://www.ourcommons.ca/Parliamentarians/en/members?view=List中提取个人名单。获得列表后,我会浏览每个成员的链接并尝试找到他们的电子邮件地址。

一些成员没有电子邮件,因此代码失败。我尝试添加匹配结果为无的代码,在这种情况下我得到重复的结果。

我正在使用以下逻辑进行匹配

mat = re.search(r'mailto:\w*\.\w*@parl.gc.ca',ln1.get('href'))
    if mat:
        email.append(mat.group())
    else:
        email.append("No Email Found")

if 条件是问题所在。当我使用 else 时,它​​会为每一行提供一次“未找到电子邮件”。

weblinks=[]
email=[]

page = requests.get('https://www.ourcommons.ca/Parliamentarians/en/members?view=ListAll')
soup = BeautifulSoup(page.content, 'lxml')


for ln in soup.select(".personName > a"):
    weblinks.append("https://www.ourcommons.ca" + ln.get('href'))
    if(len(weblinks)==10):
        break  

提取电子邮件

for elnk in weblinks:
    pagedet = requests.get(elnk)
    soupdet = BeautifulSoup(pagedet.content, 'lxml')
    for ln1 in soupdet.select(".caucus > a"):
        mat = re.search(r'mailto:\w*\.\w*@parl.gc.ca',ln1.get('href'))
        if mat:
            email.append(mat.group())
        else:
            email.append("No Email Found")

print("Len Email:",len(email))

预期结果:为有一个的页面显示电子邮件,为没有的页面显示一个空白。

标签: pythonregexpandasbeautifulsouppython-requests-html

解决方案


如果检查页面DOMtwo similar elements present这就是为什么你会得到多个值。你需要设置条件来摆脱它。试试下面的代码。

weblinks=[]
email=[]

page = requests.get('https://www.ourcommons.ca/Parliamentarians/en/members?view=ListAll')
soup = BeautifulSoup(page.content, 'lxml')


for ln in soup.select(".personName > a"):
    weblinks.append("https://www.ourcommons.ca" + ln.get('href'))
    if(len(weblinks)==10):
        break


for elnk in weblinks:
    pagedet = requests.get(elnk)
    soupdet = BeautifulSoup(pagedet.content, 'lxml')
    if len(soupdet.select(".caucus > a"))> 1:
       for ln1 in soupdet.select(".caucus > :not(a[target])"):
          mat = re.search(r'mailto:\w*\.\w*@parl.gc.ca',ln1.get('href'))
          if mat:
            email.append(mat.group())
          else:
            email.append("No Email Found")
    else:
       for ln1 in soupdet.select(".caucus > a"):
         mat = re.search(r'mailto:\w*\.\w*@parl.gc.ca', ln1.get('href'))
         if mat:
             email.append(mat.group())
         else:
             email.append("No Email Found")

print(email)
print("Len Email:",len(email))

输出:

['mailto:Ziad.Aboultaif@parl.gc.ca', 'mailto:Dan.Albas@parl.gc.ca', 'mailto:harold.albrecht@parl.gc.ca', 'mailto:John.Aldag@parl.gc.ca', 'mailto:Omar.Alghabra@parl.gc.ca', 'mailto:Leona.Alleslev@parl.gc.ca', 'mailto:dean.allison@parl.gc.ca', 'No Email Found', 'No Email Found', 'mailto:Gary.Anand@parl.gc.ca']

莱恩电子邮件:10


推荐阅读