如上图,执行python代码的时候报了这样的错,一开始不知道是怎么回事,百度后发现很多答案都是说是字符编码的问题,照着做了一番,还是没能解决问题,继续报错,后面在博客园中找到了如下图的文章内容,根据文章内容提示查看了自己的代码,发现是cookies太长了,后面换行或者删除了才得以解决这个问题。
所以问题发生,得根据自己情况进行分析。我的虽然不像博客园中说的属性值长了使用了省略号,但是也是应为过长了导致了这样的问题产生。
产生此问题的主要原因,是cookies中包含中文,即字符编码的问题,如下图,点击cookies后点击右键选择Copy value进行复制值的,粘贴在代码中后,%E9%9F%A9%E5%90%8E2014 会变回中文。这时候运行代码就会报错:
Traceback (most recent call last):
File "D:\Python\Python39\lib\site-packages\requests\api.py", line 61, in request
return session.request(method=method, url=url, **kwargs)
File "D:\Python\Python39\lib\site-packages\requests\sessions.py", line 542, in request
resp = self.send(prep, **send_kwargs)
File "D:\Python\Python39\lib\site-packages\requests\sessions.py", line 655, in send
r = adapter.send(request, **kwargs)
File "D:\Python\Python39\lib\site-packages\requests\adapters.py", line 439, in send
resp = conn.urlopen(
File "D:\Python\Python39\lib\site-packages\urllib3\connectionpool.py", line 699, in urlopen
httplib_response = self._make_request(
File "D:\Python\Python39\lib\site-packages\urllib3\connectionpool.py", line 394, in _make_request
conn.request(method, url, **httplib_request_kw)
File "D:\Python\Python39\lib\site-packages\urllib3\connection.py", line 234, in request
super(HTTPConnection, self).request(method, url, body=body, headers=headers)
File "D:\Python\Python39\lib\http\client.py", line 1257, in request
self._send_request(method, url, body, headers, encode_chunked)
File "D:\Python\Python39\lib\http\client.py", line 1298, in _send_request
self.putheader(hdr, value)
File "D:\Python\Python39\lib\site-packages\urllib3\connection.py", line 219, in putheader
_HTTPConnection.putheader(self, header, *values)
File "D:\Python\Python39\lib\http\client.py", line 1230, in putheader
values[i] = one_value.encode('latin-1')
UnicodeEncodeError: 'latin-1' codec can't encode characters in position 111-112: ordinal not in range(256)
python-BaseException
Process finished with exit code 1
所以解决这个问题,首先检查字符串中是否有中文字符,其次看看字符串一行显示是否是过长,过长的话进行换行显示。