python --- request返回值乱码问题
2024-09-02 04:07:54
1、分析
a)《HTTP权威指南》里第16章国际化里提到,如果HTTP响应中Content-Type字段没有指定charset,则默认页面是'ISO-8859-1'编码。一般现在页面编码都直接在html页面中
这处理英文页面当然没有问题,但是中文页面,就会有乱码了!
b)分析requests的源代码发现,content是urllib3读取回来的原始字节码,而text不过是尝试对content通过编码方式解码为unicode,即text返回的是处理过的Unicode型的数据,而使用content返回的是bytes型的原始数据,程序只通过http响应首部获取编码,假如响应中,没有指定charset, 那么直接返回'ISO-8859-1'。
c)本文中返回的html编码为utf-8,所以解码时出现了问题
2、解决办法
a)requests模块中自带该属性,但默认并没有用上,所以我们可以直接执行encoding为正确编码,让response.text正确解码即可
import requests
url = 'http://192.168.127.129/bugfree/index.php/site/login'
data = {
'username': 'admin',
'password': '',
'language': 'zh_cn',
'rememberMe': ''
} header = {
'User-Agent': 'Mozilla/5.0'
} cookie = {
'1_product': 'a6c11f988efefbf5398458aaf673011a504bf08ds%3A1%3A%221%22%3B',
'pageSize': '6f3ba80f2ac7df7b59e81c6cacbe4c041c5a706ds%3A2%3A%2220%22%3B',
'PHPSESSID': 'ku858m8vbmli7hp4inic0pifh7',
'language': 'bece46be16477e1ab82f9d40a53074cb0a54e105s%3A5%3A%22zh_cn%22%3B'
} res = requests.post(url,data,headers=header,cookies=cookie)
res.encoding = res.apparent_encoding
print(res.text)
b)由于content是HTTP相应的原始字节串,所以我们需要直接可以通过使用它。把content按照页面编码方式解码为unicode!
import requests
url = 'http://192.168.127.129/bugfree/index.php/site/login'
data = {
'username': 'admin',
'password': '',
'language': 'zh_cn',
'rememberMe': ''
} header = {
'User-Agent': 'Mozilla/5.0'
} cookie = {
'1_product': 'a6c11f988efefbf5398458aaf673011a504bf08ds%3A1%3A%221%22%3B',
'pageSize': '6f3ba80f2ac7df7b59e81c6cacbe4c041c5a706ds%3A2%3A%2220%22%3B',
'PHPSESSID': 'ku858m8vbmli7hp4inic0pifh7',
'language': 'bece46be16477e1ab82f9d40a53074cb0a54e105s%3A5%3A%22zh_cn%22%3B'
} res = requests.post(url,data,headers=header,cookies=cookie)
print(res.content.decode('utf-8'))
解决前:
解决后:
参考博文:https://www.cnblogs.com/bitpeng/p/4748872.html;
https://blog.csdn.net/feixuedongji/article/details/82984583
最新文章
- Eclipse安装svn插件的几种方式
- codeforces 754D. Fedor and coupons
- Bootstrap_导航
- 锋利的jQuery-3--$()创建节点
- POJ C++程序设计 编程题#2 编程作业—多态与虚函数
- 相对完美的后台Service实现播放音乐功能
- HUD 1251 难题统计
- Excel中将时间格式转化成时间戳格式
- [IOS]UIWebView 请求网络页面或者加载本地资源页面
- XSD (xml Schema Definition)
- 【原创】纯OO:从设计到编码写一个FlappyBird (五)
- html5权威指南:标记文字
- First blogs start
- UINavigationItem不显示
- mybatis取数据库为null的字段
- 做了两年多salesforce平台开发,转Java的经历
- composer在update时提示file could not be downloaded: SSL operation failed with code 1. OpenSSL Error messages: error:1407742E:SSL routines:SSL23_GET_SERVER_HELLO
- Python链接Mssql之Python库pymssql
- mysql数据库基础语句训练题
- 【小程序】当遇到bindTap绑定无法跳转到tabbar页面时
热门文章
- Zookeeper集群搭建(单机多节点,伪集群,docker-compose集群)
- redis api-hash
- 45 孩子们的游戏(圆圈中最后剩下的数) + list操作总结+ for_each多记忆容易忘记
- DRF项目之自定义分页器
- IDEA开发spring boot应用时 application.yml 或 application.properties 自定义属性提示
- Codeforces Forethought Future Cup Elimination Round 选做
- Phoenix5.0的部署
- python scipy样条插值函数大全(interpolate里interpld函数)
- JuJu团队12月4号工作汇报
- python基础数据类型--元组(tuple)