Python,格式化re.findall()输出

Python,格式化re.findall()输出,python,regex,python-3.x,Python,Regex,Python 3.x,我正在努力掌握Python中的正则表达式。我正在写一个非常简单的脚本来从给定的URL中删除电子邮件 import re from urllib.request import * url = input("Please insert the URL you wish to scrape> ") page = urlopen(url) content = page.read() email_string = b'[a-z0-9_. A-Z]*@[a-z0-9_. A-Z]*.[a-z

我正在努力掌握Python中的正则表达式。我正在写一个非常简单的脚本来从给定的URL中删除电子邮件

import re
from urllib.request import *


url = input("Please insert the URL you wish to scrape> ")

page = urlopen(url)

content = page.read()

email_string = b'[a-z0-9_. A-Z]*@[a-z0-9_. A-Z]*.[a-zA-Z]'

emails_in_page = re.findall(email_string, content)

print("Here are the emails found: ")

for email in emails_in_page:
    print(email)
re.findall()返回一个列表,当程序打印出电子邮件时,正则表达式字符串中的“b”将包含在输出中,如下所示:

b'email1@email.com'
b'email2@email.com'
...

我怎样才能打印出一份干净的电子邮件列表?(即:
email1@email.com

您正在打印
字节
对象。将它们解码为字符串:

encoding = page.headers.get_param('charset')
if encoding is None:
    encoding = 'utf8'  # sensible default

for email in emails_in_page:
    print(email.decode(encoding))
或解码检索到的HTML页面:

encoding = page.headers.get_param('charset')
if encoding is None:
    encoding = 'utf8'  # sensible default

content = page.read().decode(encoding)
并使用unicode字符串正则表达式:

email_string = '[a-z0-9_. A-Z]*@[a-z0-9_. A-Z]*.[a-zA-Z]'
许多网页在内容类型标题中没有发送正确的字符集参数,或者设置错误,因此即使是“合理默认值”也可能不时出错

像这样的HTML解析库在编解码器检测方面做得更好,它还包括一些更多的启发式方法来进行有根据的猜测:

from bs4 import BeautifulSoup

soup = BeautifulSoup(page.read(), from_encoding=page.headers.get_param('charset'))
for textelem in soup.find_all(text=re.compile(email_string)):
    print(textelem)

谢谢你,Martijn,当我运行你的代码(解码字节对象,而不是HTML)时,我得到以下信息:回溯(最近一次调用):文件“simple_scraper.py”,第11行,在encoding=page.headers.getparam('charset')AttributeError中:'HTTPMessage'对象没有属性'getparam',为什么拒绝本地部分的
+
符号?