关于爬取网页的编码问题(基于requests模块的见解)
本帖最后由 snail:) 于 2018-2-24 11:41 编辑今天遇到的一个爬虫编码问题,有时候requests模块解码会出现乱码问题:
import requests
url = 'http://tjj.zj.gov.cn/tjsj/ydsj/gy/2017/201702/t20170224_192095.html'
headers = {'user-agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'}
html = requests.get(url,headers = headers)
#print(html.encoding) 这里打印出来的是‘ISO-8859-1’,而元网址上的编码是‘utf-8’
encoding = html.encoding#获取requests模块自动解码的编码形式(可能这里与原网站写的编码形式不同)
with open('data.txt','w',encoding = encoding)as f:
f.write(html.text)
相反urllib.request模块不会出现上述编码与原网编码不一致的情况,下面是代码:
import urllib.request
url = 'http://tjj.zj.gov.cn/tjsj/ydsj/gy/2017/201702/t20170224_192095.html'
headers = {'user-agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'}
req = urllib.request.Request(url)
req.add_header('user-agent','Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36')
response = urllib.request.urlopen(req)
html = response.read().decode('utf-8')
with open('data.txt','w',encoding = 'utf-8')as f:
f.write(html)
个人见解:requests模块会自以为是的解码成他认为的最佳状态,这时候就需要手动获取html.encoding 有道理 alltolove 发表于 2018-2-24 12:28
有道理
新人,还在继续学习python,requests模块确实强大
页:
[1]