解决Requests中文乱码
来源:互联网 发布:sqlserver创建实例过程 编辑:程序博客网 时间:2024/06/08 12:15
都在推荐用Requests库,而不是Urllib,但是读取网页的时候中文会出现乱码。
分析:
r = requests.get(“http://www.baidu.com“)
**r.text返回的是Unicode型的数据。
使用r.content返回的是bytes型的数据。
也就是说,如果你想取文本,可以通过r.text。
如果想取图片,文件,则可以通过r.content。**
获取一个网页的内容
方法1:使用r.content,得到的是bytes型,再转为str
url='http://music.baidu.com'r = requests.get(url)html=r.contenthtml_doc=str(html,'utf-8') #html_doc=html.decode("utf-8","ignore")print(html_doc)
方法2:使用r.text
Requests 会自动解码来自服务器的内容。大多数 unicode 字符集都能被无缝地解码。请求发出后,Requests 会基于 HTTP 头部对响应的编码作出有根据的推测。当你访问 r.text 之时,Requests 会使用其推测的文本编码。你可以找出 Requests 使用了什么编码,并且能够使用 r.encoding 属性来改变它.
但是Requests库的自身编码为: r.encoding = ‘ISO-8859-1’
可以 r.encoding 修改编码
url='http://music.baidu.com'r=requests.get(url)r.encoding='utf-8'print(r.text)
获取一个网页的内容后存储到本地
方法1:r.content为bytes型,则open时需要open(filename,”wb”)
r=requests.get("music.baidu.com")html=r.contentwith open('test5.html','wb') as f: f.write(html)
方法2:r.content为bytes型,转为str后存储
r = requests.get("http://www.baidu.com")html=r.contenthtml_doc=str(html,'utf-8') #html_doc=html.decode("utf-8","ignore")# print(html_doc)with open('test5.html','w',encoding="utf-8") as f: f.write(html_doc)
方法3:r.text为str,可以直接存储
r=requests.get("http://www.baidu.com")r.encoding='utf-8'html=r.textwith open('test6.html','w',encoding="utf-8") as f: f.write(html)
Requests+lxml
# -*-coding:utf8-*-import requestsfrom lxml import etreeurl="http://music.baidu.com"r=requests.get(url)r.encoding="utf-8"html=r.text# print(html)selector = etree.HTML(html)title=selector.xpath('//title/text()')print (title[0])
结果为:百度音乐-听到极致
终极解决方法
以上的方法虽然不会出现乱码,但是保存下来的网页,图片不显示,只显示文本。而且打开速度慢,找到了一篇博客,提出了一个终极方法,非常棒。
来自博客
http://blog.chinaunix.net/uid-13869856-id-5747417.html的解决方案:
# -*-coding:utf8-*-import requestsreq = requests.get("http://news.sina.com.cn/")if req.encoding == 'ISO-8859-1': encodings = requests.utils.get_encodings_from_content(req.text) if encodings: encoding = encodings[0] else: encoding = req.apparent_encoding # encode_content = req.content.decode(encoding, 'replace').encode('utf-8', 'replace') global encode_content encode_content = req.content.decode(encoding, 'replace') #如果设置为replace,则会用?取代非法字符;print(encode_content)with open('test.html','w',encoding='utf-8') as f: f.write(encode_content)
- 解决Requests中文乱码
- 解决Requests中文乱码
- 解决Requests抓取时中文乱码
- python使用requests爬取网页,遇到中文出现乱码的编码问题及解决
- Python+Requests安装及抓取网页源码中文乱码问题的解决
- Python+Requests抓取中文乱码改进方案
- Python requests库中文乱码问题
- python使用requests爬取网页,遇到中文出现遇到中文出现乱码的编码问题及解决乱码的编码问题及解决
- 解决中文乱码问题
- Servlet 中文乱码解决
- ajax中文乱码解决
- Servlet 中文乱码解决
- 解决中文乱码问题
- 解决中文乱码问题
- 解决Struts中文乱码
- 过滤器解决中文乱码
- 中文乱码解决
- 解决中文乱码问题
- SQL Server - 开窗函数
- shallow size
- Android开发笔记(一百三十)截图和录屏
- 初试-基于神经网络的植物识别
- JS日期比较的一个小技巧
- 解决Requests中文乱码
- VTK修炼之道60:体绘制_体绘制管线&图形渲染管线
- NIO与传统IO的区别
- [iOS]iOS中boolean、Boolean、BOOL、bool的区别
- css link和@import区别
- MapReduce的理解
- opencv-SVM
- Html5 Canvas 系列_绘图三(H5 绘制圆弧)
- 思维导图中插入电子邮箱的教程