python - 我似乎无法在 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))
预期结果:为有一个的页面显示电子邮件,为没有的页面显示一个空白。
解决方案
如果检查页面DOM
,two 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
推荐阅读
- python - python中的奇怪赋值
- azure - Azure Active Directory - 缺少 Dynamics CRM Online (Microsoft.CRM) 所需的权限
- asp.net-core - 如何从控制器(而不是 StartUp.cs)为 IdentityOptions 设置值?
- python-2.7 - 通过 Python 保存 ODB 文件:尝试截断只读表时出错
- driver - 在 V4L2 中选择多个通道
- python - Matplotlib 切断放置在轴外的图例,忽略 savefig 中的 bbox_extra_artists 参数
- javascript - Lodash keyBy 与数组相同的属性
- python - 无法让我的程序生成随机卡片(1-13)
- c# - 在 DataTemplate UWP 中将点击器绑定到 VM
- php - PHP继承构造函数不起作用