【问题标题】:Unexpected result when parsing with BeautifulSoup and regex使用 BeautifulSoup 和正则表达式解析时出现意外结果
【发布时间】:2017-05-09 08:02:15
【问题描述】:

我正在玩 BeautifulSoup 库。我试图解析来自该网站的电子邮件,但得到了意想不到的结果。这是我的代码:

from urllib.request import urlopen
from urllib.error import HTTPError
from urllib.error import URLError

from bs4 import BeautifulSoup
import re
from urllib.parse import quote 

startUrl = "http://getrocketbook.com/pages/returns"
try:
    html = urlopen(quote((startUrl).encode('utf8'), ':/?%#_'))
    bsObj = BeautifulSoup(html, "html.parser")
    alls = bsObj.body.findAll(text=re.compile('[A-Za-z0-9\._+-]+@[A-Za-z0-9\.-]+'))
    for al in alls:
        print(al)
except HTTPError:
    pass
except URLError:
    pass

我希望只解析一封电子邮件,但实际上我解析了这个句子:

If you’ve done all of this and you still have not received your refund yet, please contact us at hello@getrocketbook.com.

知道我做错了什么吗?

【问题讨论】:

    标签: python regex beautifulsoup


    【解决方案1】:

    这是因为findAll() 查找实际元素或文本节点,而不是单独的单词。

    您需要做的是将相同的编译正则表达式应用于结果

    pattern = re.compile('[A-Za-z0-9\._+-]+@[A-Za-z0-9\.-]+')
    alls = bsObj.body.find_all(text=pattern)
    for al in alls:
        print(pattern.search(al).group(0))
    

    另外,由于那里只有一封电子邮件,请查看是否可以改用find() 方法。

    【讨论】:

      猜你喜欢
      • 2012-05-26
      • 2016-05-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-20
      • 2020-10-20
      • 1970-01-01
      • 2015-02-06
      • 1970-01-01
      相关资源
      最近更新 更多