requests.get()获取网页中文乱码的问题解决方案

摘自博客《https://blog.csdn.net/chaowanghn/article/details/54889835》留作备份。

都在推荐用Requests库,而不是Urllib,但是读取网页的时候中文会出现乱码。

分析: 
r = requests.get(“http://www.baidu.com“) 
**r.text返回的是Unicode型的数据。 
使用r.content返回的是bytes型的数据。 
也就是说,如果你想取文本,可以通过r.text。 
如果想取图片,文件,则可以通过r.content。**

获取一个网页的内容

方法1:使用r.content,得到的是bytes型,再转为str

1 url='http://music.baidu.com'
2 r = requests.get(url)
3 html=r.content
4 html_doc=str(html,'utf-8') #html_doc=html.decode("utf-8","ignore")
5 print(html_doc)

方法2:使用r.text 
Requests 会自动解码来自服务器的内容。大多数 unicode 字符集都能被无缝地解码。请求发出后,Requests 会基于 HTTP 头部对响应的编码作出有根据的推测。当你访问 r.text 之时,Requests 会使用其推测的文本编码。你可以找出 Requests 使用了什么编码,并且能够使用 r.encoding 属性来改变它. 
但是Requests库的自身编码为: r.encoding = ‘ISO-8859-1’ 
可以 r.encoding 修改编码

1 url='http://music.baidu.com'
2 r=requests.get(url)
3 r.encoding='utf-8'
4 print(r.text)

获取一个网页的内容后存储到本地

方法1:r.content为bytes型,则open时需要open(filename,”wb”)

1 r=requests.get("music.baidu.com")
2 html=r.content
3 with open('test5.html','wb') as f:
4     f.write(html)

方法2:r.content为bytes型,转为str后存储

1 r = requests.get("http://www.baidu.com")
2 html=r.content
3 html_doc=str(html,'utf-8') #html_doc=html.decode("utf-8","ignore")
4 # print(html_doc)
5 with open('test5.html','w',encoding="utf-8") as f:
6     f.write(html_doc)

方法3:r.text为str,可以直接存储

1 r=requests.get("http://www.baidu.com")
2 r.encoding='utf-8'
3 html=r.text
4 with open('test6.html','w',encoding="utf-8") as f:
5     f.write(html)

Requests+lxml

 1 # -*-coding:utf8-*-
 2 import requests
 3 from lxml import etree
 4 
 5 url="http://music.baidu.com"
 6 r=requests.get(url)
 7 r.encoding="utf-8"
 8 html=r.text
 9 # print(html)
10 selector = etree.HTML(html)
11 title=selector.xpath('//title/text()')
12 print (title[0])

结果为:百度音乐-听到极致

终极解决方法

以上的方法虽然不会出现乱码,但是保存下来的网页,图片不显示,只显示文本。而且打开速度慢,找到了一篇博客,提出了一个终极方法,非常棒。

来自博客 
http://blog.chinaunix.net/uid-13869856-id-5747417.html的解决方案:

 1 # -*-coding:utf8-*-
 2 
 3 import requests
 4 
 5 req = requests.get("http://news.sina.com.cn/")
 6 
 7 if req.encoding == 'ISO-8859-1':
 8     encodings = requests.utils.get_encodings_from_content(req.text)
 9     if encodings:
10         encoding = encodings[0]
11     else:
12         encoding = req.apparent_encoding
13 
14     # encode_content = req.content.decode(encoding, 'replace').encode('utf-8', 'replace')
15     global encode_content
16     encode_content = req.content.decode(encoding, 'replace') #如果设置为replace,则会用?取代非法字符;
17 
18 
19 print(encode_content)
20 
21 with open('test.html','w',encoding='utf-8') as f:
22     f.write(encode_content)
原文地址:https://www.cnblogs.com/cainiao-xf/p/8884278.html