Python requests库中文乱码问题

当使用requests库的时候,会出现中文乱码的情况

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

      Python HTTP库requests中文页面乱码解决方案!

分析

根据这两篇文章可知:

    分析requests的源代码发现,text返回的是处理过的Unicode型的数据,而使用content返回的是bytes型的原始数据。也就是说,r.content相对于r.text来说节省了计算资源,content是把内容bytes返回. 而text是decode成Unicode. 如果headers没有charset字符集的化,text()会调用chardet来计算字符集,这又是消耗cpu的事情.

1
2
3
4
import  requests
 
response  =  requests.get( 'http://www.dytt8.net/index.htm' )
print (response.text[ 200 : 300 ])

这里测试使用电影天堂的网页,因为网页不太标准

输出为

  

输出了乱码

response.encoding

从第二篇文章可以知道reqponse header只指定了type,但是没有指定编码(一般现在页面编码都直接在html页面中),查找原网页可以看到

再找一个标准点的网页查看,比如博客园的网页博客园

response herders的Content-Type指定了编码类型

《HTTP权威指南》里第16章国际化里提到,如果HTTP响应中Content-Type字段没有指定charset,则默认页面是'ISO-8859-1'编码。这处理英文页面当然没有问题,但是中文页面,就会有乱码了!

解决

如果在确定使用text,并已经得知该站的字符集编码时,可以使用 r.encoding = ‘xxx’ 模式, 当你指定编码后,requests在text时会根据你设定的字符集编码进行转换. 

使用apparent_encoding可以获得真实编码

1
2
>>> response.apparent_encoding
'GB2312'

这是程序自己分析的,会比较慢

还可以从html的meta中抽取

1
2
>>> requests.utils.get_encodings_from_content(response.text)
[ 'gb2312' ]

解决方法

1
2
# response.encoding = response.apparent_encoding
response.encoding  =  'gb2312'

这时候的输出为

  

  

问题: python requests 爬取网页乱码 回答: 当使用Pythonrequests爬取网页时,有时会遇到网页乱码的问题。解决这个问题的方法有几种。一种方法是在获取网页内容后,使用response.encoding属性来设置编码格式。例如,可以将response.encoding设置为'utf-8'来解决乱码问题。\[1\] 另一种方法是使用response.apparent_encoding属性来获取网页的实际编码格式,然后将response.encoding设置为该编码格式。这样可以更准确地解决乱码问题。例如,可以使用response.apparent_encoding来获取网页的实际编码格式,然后将response.encoding设置为该编码格式,如response.encoding = response.apparent_encoding。\[2\] 下面是一个示例代码,演示了如何使用requests解决网页乱码问题: ```python import requests url = 'https://data.stats.gov.cn/easyquery.htm?m=QueryData&dbcode=hgnd&rowcode=zb&colcode=sj&wds=%5B%5D&dfwds=%5B%5D&k1=1651977499228&h=1' headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.54 Safari/537.36 Edg/101.0.1210.39' } def solveCoding(url, headers): response = requests.get(url=url, headers=headers, verify=False) response.encoding = response.apparent_encoding print(response.json()) if __name__ == '__main__': solveCoding(url=url, headers=headers) ``` 通过使用上述代码中的方法,你可以解决Python requests爬取网页乱码的问题。\[3\] #### 引用[.reference_title] - *1* *2* *3* [python 使用requests模块爬取数据时中文乱码问题](https://blog.csdn.net/weixin_48368715/article/details/124645013)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值