0.

requests不设置UA 访问baidu 得到 r.headers['Content-Type'] 是text/html  使用chrome UA: Content-Type:text/html; charset=utf-8

1.参考

代码分析Python requests库中文编码问题

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 &mdash; 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 &mdash; 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解码错误的更多相关文章

  1. Jsoup问题---获取http协议请求失败 org.jsoup.UnsupportedMimeTypeException: Unhandled content type. Must be text/*, application/xml, or application/xhtml+xml.

    Jsoup问题---获取http协议请求失败 1.问题:用Jsoup在获取一些网站的数据时,起初获取很顺利,但是在访问某浪的数据是Jsoup报错,应该是请求头里面的请求类型(ContextType)不 ...

  2. Jsoup获取部分页面数据失败 org.jsoup.UnsupportedMimeTypeException: Unhandled content type. Must be text/*, application/xml, or application/xhtml+xml.

    用Jsoup在获取一些网站的数据时,起初获取很顺利,但是在访问某浪的数据是Jsoup报错,应该是请求头里面的请求类型(ContextType)不符合要求. 请求代码如下: private static ...

  3. Jsoup获取部分页面数据失败 Unhandled content type. Must be text/*, application/xml, or application/xhtml+xml

    用Jsoup在获取一些网站的数据时,起初获取很顺利,但是在访问某浪的数据是Jsoup报错,应该是请求头里面的请求类型(ContextType)不符合要求. 请求代码如下: private static ...

  4. {"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 ...

  5. 遇到问题之“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 ...

  6. 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 ...

  7. Jmeter发送post请求报错Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported

    常识普及: Content-type,在Request Headers里面,告诉服务器,我们发送的请求信息格式,在JMeter中,信息头存储在信息头管理器中,所以在做接口测试的时候,我们维护Conte ...

  8. 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- ...

  9. SharePoint自动化系列——Add content type to list.

    转载请注明出自天外归云的博客园:http://www.cnblogs.com/LanTianYou/ 将创建好的content type(若是跨web application需要事先publish c ...

随机推荐

  1. vue中@contextmenu在pc和mac中的区别

    项目中有用到右键菜单,故用了@contextmenu,由于本人是用的PC电脑,所以一切正常, 但是有同事用mac测试了一下,问题随之而来,MAC上右键按下就触发了, PC上面是鼠标抬起才会触发,所以这 ...

  2. C. Multiplicity 简单数论+dp(dp[i][j]=dp[i-1][j-1]+dp[i-1][j] 前面序列要满足才能构成后面序列)+sort

    题意:给出n 个数 的序列 问 从n个数删去任意个数  删去的数后的序列b1 b2 b3 ......bk  k|bk 思路: 这种题目都有一个特性 就是取到bk 的时候 需要前面有个bk-1的序列前 ...

  3. [洛谷P2107] 小Z的AK计划

    题目类型:贪心,堆 传送门:>Here< 题意:给出\(N\)个房间,每个房间距离起点的距离为\(x[i]\),每个房间可以选择进去和不进去,如果进去了那么要\(t[i]\)秒后才能出来. ...

  4. CAN总线为什么要有两个120Ω的终端电阻?

    1  CAN总线为什么要有两个120Ω的终端电阻? 2 终端电阻的作用是使阻抗连续,消除反射,那为什么只在物理上最远的两个节点加这个匹配电阻,而不是在所有的节点都加上匹配电阻? 高频信号传输时,信号波 ...

  5. 洛谷P1233 木棍加工题解 LIS

    突然发现自己把原来学的LIS都忘完了,正好碰见这一道题.|-_-| \(LIS\),也就是最长上升子序列,也就是序列中元素严格单调递增,这个东西有\(n^{2}\)和\(nlog_{2}n\)两种算法 ...

  6. Day045--DOM操作

    一. 操作DOM的三步走 - 获取事件源 (找开关) - 事件(点一下) - 处理程序(业务逻辑)(灯亮了) 二. 获取DOM的三种方式 console.log(window); // 查看windo ...

  7. c/c++学习系列之memset()函数

    [转载] memset 函数是内存赋值函数,用来给某一块内存空间进行赋值的: 包含在<string.h>头文件中,可以用它对一片内存空间逐字节进行初始化: 原型为 : void *mems ...

  8. c语言中堆栈和静态空间

    什么是堆空间.栈空间与静态空间 堆空间:由程序员自己分配空间,如malloc需要指定分配多少个多大的字节空间,不用的时候需要自己释放 栈空间:栈空间是由系统自动分配与释放,如int,char等大小都已 ...

  9. 金融量化分析【day111】:Matplotib简介

    一.Matplotib-绘图和可视化简介 Matplotib是一个强大的Python绘图和数据可视化的工具包 1.安装方法 pip install matplotlib 2.引用方法 import m ...

  10. Hive SQL 分类

    题目: 请使用Hive SQL实现下面的题目. 下面是一张表名为user_buy_log的表,有三个字段,user(用户),grp(分组编号),time(购物时间). 需要将用户按照grp分组,对ti ...