python爬虫,读取本地html时编码报错:UnicodeDecodeError: 'ascii' codec can't decode

Python07

python爬虫,读取本地html时编码报错:UnicodeDecodeError: 'ascii' codec can't decode,第1张

Beautiful Soup自动将输入文档转换为Unicode编码,输出文档转换为utf-8编码。你不需要考虑编码方式,除非文档没有指定一个编码方式,这时,Beautiful Soup就不能自动识别编码方式了。然后,你仅仅需要说明一下原始编码方式就可以了。

python3 区分了 unicode str 和 byte arrary,并且默认编码不再是 ascii

关于编码问题的终极解决方案:

在python的Lib\site-packages文件夹下新建一个sitecustomize.py

文件,输入:

import sys

sys.setdefaultencoding('gb2312')

这里要注意一点是:这里面你可以设置GBK或者utf8 或者其他类型的编码格式,不一定非要gb2312,主要看你操作的环境需要什么编码格式

mport urllib.request

import re

def getHtml(url):

page = urllib.request.urlopen(url)

html = page.read()

html = html.decode('GBK')

return html

def getMeg(html):

reg = re.compile(r'******')

meglist = re.findall(reg,html)

for meg in meglist:

with open('out.txt',mode='a',encoding='utf-8') as file:

file.write('%s\n' % meg)

if __name__ == "__main__":

html = getHtml(url)

getMeg(html)

可以使用Python自带的HTMLParser模块解析HTML文档:

HTMLParser的核心模块是org.htmlparser.Parser类,这个类实际完成了对于HTML页面的分析工作。这个类有下面几个构造函数:

public Parser ()

public Parser (Lexer lexer, ParserFeedback fb)

public Parser (URLConnection connection, ParserFeedback fb) throws ParserException

public Parser (String resource, ParserFeedback feedback) throws ParserException

public Parser (String resource) throws ParserException

public Parser (Lexer lexer)

public Parser (URLConnection connection) throws ParserException

和一个静态类public static Parser createParser (String html, String charset)