requests之headers 'Content-Type': 'text/html'误判encoding为'ISO-8859-1'导致中文text解码错误
0.
requests不设置UA 访问baidu 得到 r.headers['Content-Type'] 是text/html 使用chrome UA: Content-Type:text/html; charset=utf-8
1.参考
iso-8859是什么? 他又被叫做Latin-1或“西欧语言”
补丁:
import requests
def monkey_patch():
prop = requests.models.Response.content
def content(self):
_content = prop.fget(self)
if self.encoding == 'ISO-8859-1':
encodings = requests.utils.get_encodings_from_content(_content)
if encodings:
self.encoding = encodings[0]
else:
self.encoding = self.apparent_encoding
_content = _content.decode(self.encoding, 'replace').encode('utf8', 'replace')
self._content = _content
return _content
requests.models.Response.content = property(content)
monkey_patch()
2.原因
In [291]: r = requests.get('http://cn.python-requests.org/en/latest/')
In [292]: r.headers.get('content-type')
Out[292]: 'text/html; charset=utf-8'
In [293]: r.encoding
Out[293]: 'utf-8'
In [294]: rc = requests.get('http://python3-cookbook.readthedocs.io/zh_CN/latest/index.html')
In [296]: rc.headers.get('content-type')
Out[296]: 'text/html'
In [298]: rc.encoding
Out[298]: 'ISO-8859-1'
response text 异常
In [312]: rc.text
Out[312]: u'\n\n<!DOCTYPE html>\n<!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]-->\n<!--[if gt IE 8]><!--> <html class="no-js" lang="en" > <!--<![endif]-->\n<head>\n <meta charset="ut
f-8">\n \n <meta name="viewport" content="width=device-width, initial-scale=1.0">\n \n <title>Python Cookbook 3rd Edition Documentation — python3-cookbook 2.0.0 \xe6\x96\x87\xe6\xa1\xa3</tit
le>\n \n\n \n \n \n \n\n \n\n \n \n \n\n \n\n \n \n\n \n <link rel="stylesheet" href="https://media.readthedocs.org/css/sphinx_rtd_theme.css" type="text/css" />\n \n\n \n <l
ink rel="index" title="\xe7\xb4\xa2\xe5\xbc\x95"\n href="genindex.html"/>\n <link rel="search" title="\xe6\x90\x9c\xe7\xb4\xa2" href="search.html"/>\n <link rel="copyright"
title="\xe7\x89\x88\xe6\x9d\x83\xe6\x89\x80\xe6\x9c\x89" href="copyright.html"/>\n <link rel="top" title="python3-cookbook 2.0.0 \xe6\x96\x87\xe6\xa1\xa3" href="#"/>\n <link rel="next" title In [313]: rc.content
Out[313]: '\n\n<!DOCTYPE html>\n<!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]-->\n<!--[if gt IE 8]><!--> <html class="no-js" lang="en" > <!--<![endif]-->\n<head>\n <meta charset="utf
-8">\n \n <meta name="viewport" content="width=device-width, initial-scale=1.0">\n \n <title>Python Cookbook 3rd Edition Documentation — python3-cookbook 2.0.0 \xe6\x96\x87\xe6\xa1\xa3</titl
e>\n \n\n \n \n \n \n\n \n\n \n \n \n\n \n\n \n \n\n \n <link rel="stylesheet" href="https://media.readthedocs.org/css/sphinx_rtd_theme.css" type="text/css" />\n \n\n \n <li
nk rel="index" title="\xe7\xb4\xa2\xe5\xbc\x95"\n href="genindex.html"/>\n <link rel="search" title="\xe6\x90\x9c\xe7\xb4\xa2" href="search.html"/>\n <link rel="copyright" t
itle="\xe7\x89\x88\xe6\x9d\x83\xe6\x89\x80\xe6\x9c\x89" href="copyright.html"/>\n <link rel="top" title="python3-cookbook 2.0.0 \xe6\x96\x87\xe6\xa1\xa3" href="#"/>\n <link rel="next" title=
response headers有'content-type'而且没有charset而且有'text',同时满足三个条件导致判定'ISO-8859-1'
参考文章说 python3 没有问题,实测有。
C:\Program Files\Anaconda2\Lib\site-packages\requests\utils.py
20180102 补充:# "Content-Type": "application/json" 对应 r.encoding 为 None
def get_encoding_from_headers(headers):
"""Returns encodings from given HTTP Header Dict. :param headers: dictionary to extract encoding from.
:rtype: str
""" content_type = headers.get('content-type') if not content_type:
return None content_type, params = cgi.parse_header(content_type) if 'charset' in params:
return params['charset'].strip("'\"") if 'text' in content_type:
return 'ISO-8859-1'
C:\Program Files\Anaconda2\Lib\site-packages\requests\adapters.py
class HTTPAdapter(BaseAdapter):
def build_response(self, req, resp):
# Set encoding.
response.encoding = get_encoding_from_headers(response.headers)
3.解决办法
参考文章打补丁或:
20180102 补充: if resp.encoding == 'ISO-8859-1': 修改为 if r.encoding == 'ISO-8859-1' and not 'ISO-8859-1' in headers.get('content-type', ''): 即只处理按照协议最后返回的 'ISO-8859-1'
if r.encoding == 'ISO-8859-1' and not 'ISO-8859-1' in headers.get('content-type', ''):
encodings = requests.utils.get_encodings_from_content(resp.content) #re.compile(r'<meta.*?charset #源代码没有利用这个方法
if encodings:
resp.encoding = encodings[0]
else:
resp.encoding = resp.apparent_encoding #models.py chardet.detect(self.content)['encoding'] 消耗计算 # resp.text >>> if self.encoding is None: encoding = self.apparent_encoding
print 'ISO-8859-1 changed to %s'%resp.encoding
requests之headers 'Content-Type': 'text/html'误判encoding为'ISO-8859-1'导致中文text解码错误的更多相关文章
- Jsoup问题---获取http协议请求失败 org.jsoup.UnsupportedMimeTypeException: Unhandled content type. Must be text/*, application/xml, or application/xhtml+xml.
Jsoup问题---获取http协议请求失败 1.问题:用Jsoup在获取一些网站的数据时,起初获取很顺利,但是在访问某浪的数据是Jsoup报错,应该是请求头里面的请求类型(ContextType)不 ...
- Jsoup获取部分页面数据失败 org.jsoup.UnsupportedMimeTypeException: Unhandled content type. Must be text/*, application/xml, or application/xhtml+xml.
用Jsoup在获取一些网站的数据时,起初获取很顺利,但是在访问某浪的数据是Jsoup报错,应该是请求头里面的请求类型(ContextType)不符合要求. 请求代码如下: private static ...
- Jsoup获取部分页面数据失败 Unhandled content type. Must be text/*, application/xml, or application/xhtml+xml
用Jsoup在获取一些网站的数据时,起初获取很顺利,但是在访问某浪的数据是Jsoup报错,应该是请求头里面的请求类型(ContextType)不符合要求. 请求代码如下: private static ...
- {"timestamp":"2019-11-12T02:39:28.949+0000","status":415,"error":"Unsupported Media Type","message":"Content type 'text/plain;charset=UTF-8' not supported","path":&quo
在Jmeter运行http请求时报错: {"timestamp":"2019-11-12T02:39:28.949+0000","status&quo ...
- 遇到问题之“postman报Unsupported Media Type: Content type 'text/plain;charset=UTF-8' not supported”
postman报Unsupported Media Type: Content type 'text/plain;charset=UTF-8' not supported postman之所以报Uns ...
- the request doesn't contain a multipart/form-data or multipart/form-data stream, content type header
the request doesn't contain a multipart/form-data or multipart/form-data stream, content type header ...
- Jmeter发送post请求报错Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported
常识普及: Content-type,在Request Headers里面,告诉服务器,我们发送的请求信息格式,在JMeter中,信息头存储在信息头管理器中,所以在做接口测试的时候,我们维护Conte ...
- Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported
Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported告诉你,你的请求头是application/x- ...
- SharePoint自动化系列——Add content type to list.
转载请注明出自天外归云的博客园:http://www.cnblogs.com/LanTianYou/ 将创建好的content type(若是跨web application需要事先publish c ...
随机推荐
- 初识服务器和Linux
一.什么是计算机 1.介绍 一说到计算机,我们首先想到的就是电脑,没错,电脑就是计算机,但是计算机不只是电脑. 所谓的电脑就是一种计算机,而计算机其实是:接收使用者输入的指令与资料,经中央处理器的数学 ...
- GitHub最基本使用总结
GitHub最基本使用入门 入门必看博客:https://mp.weixin.qq.com/s/LbzSwl4dYwrSPze0w10l8w 一.Git Linux安装 Git Linux安装教程:h ...
- 数据分析---《Python for Data Analysis》学习笔记【02】
<Python for Data Analysis>一书由Wes Mckinney所著,中文译名是<利用Python进行数据分析>.这里记录一下学习过程,其中有些方法和书中不同 ...
- Time travel HDU - 4418(高斯消元)
Agent K is one of the greatest agents in a secret organization called Men in Black. Once he needs to ...
- luogu4705玩游戏
题解 我们要对于每个t,求一个(1/mn)sigma(ax+by)^t. 把系数不用管,把其他部分二项式展开一下: simga(ax^r*by^(t-r)*C(t,r)). 把组合数拆开,就变成了一个 ...
- JSTL和EL的使用
JSTL和EL的使用 使用JSTL前的准备 想要使用JSTL,首先需要给工程导入JSTL的包(JSTL.jar和standard.jar). JSTL标签库 在JSTL中分为以下五个标签 核心标签 格 ...
- ElasticSearch6.5.0 【Java客户端之REST Client】
说明 High Level Client 是基于 Low Level Client 的.官方文档如下: * https://www.elastic.co/guide/en/elasticsearch/ ...
- mysql快速生成批量测试数据
mysql快速生成批量测试数据 参考资料: https://blog.csdn.net/oahz4699092zhao/article/details/53332148 -- 创建一个临时内存表 ; ...
- Decision tree(决策树)算法初探
0. 算法概述 决策树(decision tree)是一种基本的分类与回归方法.决策树模型呈树形结构(二分类思想的算法模型往往都是树形结构) 0x1:决策树模型的不同角度理解 在分类问题中,表示基于特 ...
- idea设置JVM运行参数
对JVM运行参数进行修改是JVM性能调优的重要手段,下面介绍在应用程序开发过程中JVM参数设置的几种方式. 方式一 java程序运行时指定 -Dproperty=value 该参数通常用于设置系统级全 ...