Python3爬虫抓取网页中文输出乱码

原文链接: http://blog.sina.com.cn/s/blog_eb82ea590102w2xc.html
对于Python3爬虫抓取网页中文出现输出乱码
import urllib.request
response = urllib.request.urlopen('http://www.baidu.com')
html = response.read()
print(html)
上面的代码正常但是运行的时候结果遇到中文会以\xe7\x99\xbe\xe5\xba\xa6\xe4\xb8\x80代替,这是一种byte字节。
python 3输出位串,而不是可读的字符串,需要对其进行转换

使用str(string[, encoding])对数组进行转换

str(response.read(),'utf-8')

import urllib.request
response = urllib.request.urlopen('http://www.baidu.com')
html =str(response.read(),'utf-8')
print(html)
这样就解决了中文不能输出问题,效果如下
Python3爬虫抓取网页中文输出乱码_第1张图片



 

你可能感兴趣的:(爬虫)