【问题标题】:How to check if email exists in p tag using Beautiful Soup?如何使用 Beautiful Soup 检查 p 标签中是否存在电子邮件?
【发布时间】:2019-05-21 18:28:17
【问题描述】:

我正在使用 Beautiful Soup 来尝试检查 div 标签内的段落标签中是否有电子邮件地址。我正在循环遍历 div 列表:

for div in list_of_divs:

每个div在哪里:

<div>
  <p>Hello</p>
  <p>hereIsAnEmail@gmail.com</p>
</div>

在 for 循环中,我有:

email = div.find(name="p", string=re.compile("^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$"))

name="p" 工作正常,但我不知道该为字符串添加什么。任何帮助或指导表示赞赏。

【问题讨论】:

  • 请包含足够的代码以提供mvcereply 是什么?
  • @wpercy 抱歉,我刚刚改了代码

标签: regex python-3.x beautifulsoup


【解决方案1】:

你可以使用

html="""<div>
  <p>Hello</p>
  <p>hereIsAnEmail@gmail.com</p>
</div>"""
soup = BeautifulSoup(html, "html5lib")
list_of_divs = soup.find_all('div')
for div in list_of_divs:
    emails = div.find_all("p", string=re.compile(r"^[\w.-]+@(?:[\w-]+\.)+\w{2,4}$"))
    print([em.text for em in emails])

输出:['hereIsAnEmail@gmail.com']

请注意,^[\w.-]+@(?:[\w-]+\.)+\w{2,4}$ 的限制非常严格,您可能希望使用更通用的方法,例如匹配 1+ 个非空白字符、@、1+ 个非空白字符、.^\S+@\S+\.\S+$ 和再次 1+ 非空白字符。

代码注释:

  • 使用div.find_all("p", string=re.compile(r"^[\w.-]+@(?:[\w-]+\.)+\w{2,4}$")),您可以获得当前div 元素的所有子p 标记,其文本与正则表达式模式完全匹配
  • print([em.text for em in emails]) 仅打印所有找到的 p 节点的文本,其中仅包含电子邮件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-07
    • 2016-12-22
    • 2020-02-27
    相关资源
    最近更新 更多