用python搜索html [关闭]

问题描述 投票:0回答:2

我的问题是用Python搜索html格式。我正在使用此代码:

with urllib.request.urlopen("http://") as url:
    data = url.read().decode()

现在这将从页面返回整个HTML代码,我想提取所有电子邮件地址。

有人可以帮我一把吗?提前致谢

python html search urllib
2个回答
1
投票

使用beautifulsoup BeautifulSoupRequests你可以这样做:

import requests
from bs4 import BeautifulSoup
import re

response = requests.get("your_url")
response_text = response.text
beautiful_response = BeautifulSoup(response_text, 'html.parser')

email_regex = r'[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+'

list_of_emails = re.findall(email_regex, beautiful_response .text)
list_of_emails_decoded = []
for every_email in list_of_emails:
    list_of_emails_decoded.append(every_email.encode('utf-8'))

1
投票

请记住,您不应该使用正则表达式进行实际的HTML解析(感谢@Patrick Artner),但您可以使用漂亮的汤来提取网页上的所有可见文本或注释。然后,您可以使用此文本(只是一个字符串)来查找电子邮件地址。以下是如何做到这一点:

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的电子邮件文章为例,这里是输出:

['[email protected]', 'local-part@domain', '[email protected]', '[email protected]', 'local-part@domain', '[email protected]', 'fred+bah@domain', 'fred+foo@domain', 'fred@domain', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', 'admin@mailserver1', "#!$%&'*+-/=?^_`{}|[email protected]", '[email protected]', 'user@localserver', 'A@b', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '1234567890123456789012345678901234567890123456789012345678901234+x@example.com', '[email protected]', 'example@localhost', 'john.doe@example', '[email protected]', '[email protected]', '[email protected]', '[email protected]']
© www.soinside.com 2019 - 2024. All rights reserved.