请记住,您不应该将正则表达式用于实际的 HTML 解析(感谢@Patrick Artner),但您可以使用漂亮的汤来提取网页上所有可见的文本或 cmets。然后,您可以使用此文本(只是一个字符串)来查找电子邮件地址。以下是你可以做到的:
from bs4 import BeautifulSoup
from bs4.element import Comment
import urllib
import re
def tag_visible(element):
if element.parent.name in ['style', 'script', 'head', 'title', 'meta', '[document]']:
return False
if isinstance(element, Comment):
return False
return True
def text_from_html(body):
soup = BeautifulSoup(body, 'html.parser')
texts = soup.findAll(text=True)
visible_texts = filter(tag_visible, texts)
return u" ".join(t.strip() for t in visible_texts)
with urllib.request.urlopen("https://en.wikipedia.org/wiki/Email_address") as url:
data = url.read().decode()
text = text_from_html(data)
print(re.findall(r"[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*", text))
这两个辅助函数只是抓取页面上可以看到的所有文本,然后这个长得可笑的正则表达式只是从该文本中提取所有电子邮件地址。我以 wikipedia.com 关于电子邮件的文章为例,输出如下:
['John.Smith@example.com', 'local-part@domain', 'jsmith@example.com', 'john.smith@example.org', 'local-part@domain', 'John..Doe@example.com', 'fred+bah@domain', 'fred+foo@domain', 'fred@domain', 'john.smith@example.com', 'john.smith@example.com', 'jsmith@example.com', 'JSmith@example.com', 'john.smith@example.com', 'john.smith@example.com', 'prettyandsimple@example.com', 'very.common@example.com', 'disposable.style.email.with+symbol@example.com', 'other.email-with-dash@example.com', 'fully-qualified-domain@example.com', 'user.name+tag+sorting@example.com', 'user.name@example.com', 'x@example.com', 'example-indeed@strange-example.com', 'admin@mailserver1', "#!$%&'*+-/=?^_`{}|~@example.org", 'example@s.solutions', 'user@localserver', 'A@b', 'c@example.com', 'l@example.com', 'right@example.com', 'allowed@example.com', 'allowed@example.com', '1234567890123456789012345678901234567890123456789012345678901234+x@example.com', 'john..doe@example.com', 'example@localhost', 'john.doe@example', 'joeuser+tag@example.com', 'joeuser@example.com', 'foo+bar@example.com', 'foobar@example.com']