错误出现代码

import requests

headers = {
    'Accept': '*/*',
    'Accept-Encoding': 'gzip, deflate, br',
    'Accept-Language': 'zh-CN,zh-Hans;q=0.9',
    'Connection': 'keep-alive',
    'Content-Encoding': 'gzip',
    'Content-Length': '318',
    'Content-Type': 'application/x-www-form-urlencoded',
    'Host': 'data.bilibili.com',
    'User-Agent': '哔哩哔哩/65201100 CFNetwork/1325.0.1 Darwin/21.1.0'

}
data = '[data]'
res = requests.post('https://data.bilibili.com/log/mobile?ios', headers=headers, data=data)

错误显示

Traceback (most recent call last):
  File "C:/Users/Master/PycharmProjects/[hide]/[hide].py", line 16, in <module>
    res = requests.post('https://data.bilibili.com/log/mobile?ios', headers=headers)
  File "C:\Users\Master\AppData\Local\Programs\Python\Python38\lib\site-packages\requests\api.py", line 119, in post
    return request('post', url, data=data, json=json, **kwargs)
  File "C:\Users\Master\AppData\Local\Programs\Python\Python38\lib\site-packages\requests\api.py", line 61, in request
    return session.request(method=method, url=url, **kwargs)
  File "C:\Users\Master\AppData\Local\Programs\Python\Python38\lib\site-packages\requests\sessions.py", line 530, in request
    resp = self.send(prep, **send_kwargs)
  File "C:\Users\Master\AppData\Local\Programs\Python\Python38\lib\site-packages\requests\sessions.py", line 643, in send
    r = adapter.send(request, **kwargs)
  File "C:\Users\Master\AppData\Local\Programs\Python\Python38\lib\site-packages\requests\adapters.py", line 439, in send
    resp = conn.urlopen(
  File "C:\Users\Master\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\connectionpool.py", line 670, in urlopen
    httplib_response = self._make_request(
  File "C:\Users\Master\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\connectionpool.py", line 392, in _make_request
    conn.request(method, url, **httplib_request_kw)
  File "C:\Users\Master\AppData\Local\Programs\Python\Python38\lib\http\client.py", line 1240, in request
    self._send_request(method, url, body, headers, encode_chunked)
  File "C:\Users\Master\AppData\Local\Programs\Python\Python38\lib\http\client.py", line 1281, in _send_request
    self.putheader(hdr, value)
  File "C:\Users\Master\AppData\Local\Programs\Python\Python38\lib\http\client.py", line 1213, in putheader
    values[i] = one_value.encode('latin-1')
UnicodeEncodeError: 'latin-1' codec can't encode characters in position 0-3: ordinal not in range(256)

错误分析

考虑到无论是否输出res的内容,都会报错,因此排除是输出的问题。
怀疑是请求和接受的编码不对应,因为考虑是不是哪里的中文有问题,首先排查data的内容,检查后没有中文,最后检查请求头中,User-Agent含有中文,感觉问题就是出在这里。

错误处理(解决)

现将User-Agentencode为utf8然后decode为latin-1编码即可

'User-Agent': '哔哩哔哩/65201100 CFNetwork/1325.0.1 Darwin/21.1.0'.encode('utf-8').decode('latin-1')

同样的,如果中文出现在非User-Agnet而是其他请求头的字段中(如refer),应该用同样的方法可以处理。

Last modification:December 24th, 2021 at 12:31 am
如果我的文章对你有用,请随意赞赏,不要白嫖哦~