python_requests库请求内容出现乱码

本文介绍了解决使用request请求网页时出现中文乱码的方法,包括设置正确的编码格式和使用apparent_encoding自动检测编码。

一、有时候request会出现请求的网页内容中中文部分显示为乱码

1.通过添加encoding,可以改回来

def download_page(url):
   headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0"}
   r = requests.get(url, headers=headers)
   r.encoding = 'gb2312'
   return r.text

2.利用apparent_encoding

res = requests.get(url, headers = header)
res.encoding = res.apparent_encoding
pritn(res.text)

二、关于encoding的选择

1.查看该网页的网页源代码

charset的编码就是encoding的值

在使用 Python 的 `requests` 发送请求时,若请求参数中包含中文字符,可能会因为编码问题导致乱码。这种现象通常出现在 GET 请求的 URL 参数或 POST 请求的表单数据中。以下是几种有效的解决方法: ### GET 请求中的中文参数乱码 GET 请求的参数通常附加在 URL 后面,而 URL 只能使用 ASCII 编码。如果参数中包含非 ASCII 字符(如中文),则需要对参数进行编码。`requests` 提供了自动处理编码的功能,可以通过传递字典形式的参数来实现[^1]。 ```python import requests params = { 'key1': 'value1', 'key2': '中文' } response = requests.get('http://example.com', params=params) print(response.url) ``` 上述代码会自动将 `params` 中的中文参数进行 URL 编码,确保传输过程中不会出现乱码问题。 ### POST 请求中的中文参数乱码 POST 请求的参数通常以表单或 JSON 格式发送。对于表单数据,`requests` 默认使用 `application/x-www-form-urlencoded` 编码方式,同样可以通过传递字典来处理中文字符[^2]。 ```python import requests data = { 'username': '用户', 'password': '密码' } response = requests.post('http://example.com/login', data=data) print(response.text) ``` 如果需要发送 JSON 数据,可以使用 `json` 参数,`requests` 会自动将字典转换为 JSON 格式,并设置正确的 `Content-Type` 头部[^3]。 ```python import requests json_data = { 'username': '用户', 'password': '密码' } response = requests.post('http://example.com/login', json=json_data) print(response.text) ``` ### 手动指定编码方式 在某些情况下,服务器可能返回的响应内容中包含中文字符,但 `requests` 无法正确识别编码方式,这时可以手动指定响应的编码[^4]。 ```python import requests response = requests.get('http://example.com') response.encoding = 'utf-8' # 手动指定编码为 UTF-8 print(response.text) ``` ### 使用 `apparent_encoding` 自动检测编码 如果不确定服务器返回的内容使用哪种编码,可以使用 `apparent_encoding` 属性,它会基于响应内容进行编码猜测[^1]。 ```python import requests response = requests.get('http://example.com') response.encoding = response.apparent_encoding # 自动检测编码 print(response.text) ``` ### 直接处理二进制响应内容 对于某些特殊编码的响应内容,可以先获取二进制数据,然后手动解码为所需的字符集[^3]。 ```python import requests response = requests.get('http://example.com') print(response.content.decode('utf-8')) # 手动解码为 UTF-8 ``` ### 设置请求头中的 `Accept-Encoding` 在某些情况下,服务器可能会根据 `Accept-Encoding` 头部返回不同编码的内容。可以通过设置请求头来控制服务器返回的内容编码方式[^4]。 ```python import requests headers = { 'Accept-Encoding': 'identity' # 请求服务器不进行压缩 } response = requests.get('http://example.com', headers=headers) print(response.text) ``` --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值