python - 使用 BeautifulSoup 和正则表达式解析时出现意外结果

标签 python regex beautifulsoup

我正在使用 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 <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="49212c252526092e2c3d3b262a222c3d2b262622672a2624" rel="noreferrer noopener nofollow">[email protected]</a>.

知道我做错了什么吗?

最佳答案

这是因为 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() 方法。

关于python - 使用 BeautifulSoup 和正则表达式解析时出现意外结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41304417/

相关文章:

python - 这是广度优先搜索算法吗?

python - 将 Numpy 结构化数组转换为 Pandas 数据帧

python - 计算大数据集中点间距离的直方图

python - Beautiful Soup 在 "&quot;"和 "&lt;"等特殊字符上崩溃

python - "module object is not callable"是什么意思?

python - 在 BeautifulSoup 中索引多个表

python - python中特殊符号前后插入空格

python - 如何从 ip link show 命令中拆分行?

javascript - 前 n 个匹配项的正则表达式

javascript - 匹配字符串,除非以字符开头和结尾