我正在使用 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/