requests 遇到报错UnicodeEncodeError: 'latin-1' codec can't encode character '\u86c7' in position 8: Body ('蛇') is not valid Latin-1. Use body.encode('utf-8') if you want to send it encoded in UTF-8.

错误描述

Traceback (most recent call last):
  File "C:/Users/zuimojun/PycharmProjects/pythonProject4/requestdata/readexcl.py", line 23, in <module>
    print(rc.requestsExcelMethod())
  File "C:/Users/zuimojun/PycharmProjects/pythonProject4/requestdata/readexcl.py", line 17, in requestsExcelMethod
    rr = requests.post(excel_i["url"], data=excel_i["params"])
  File "C:\Users\zuimojun\AppData\Local\Programs\Python\Python37\lib\site-packages\requests\api.py", line 116, in post
    return request('post', url, data=data, json=json, **kwargs)
  File "C:\Users\zuimojun\AppData\Local\Programs\Python\Python37\lib\site-packages\requests\api.py", line 60, in request
    return session.request(method=method, url=url, **kwargs)
  File "C:\Users\zuimojun\AppData\Local\Programs\Python\Python37\lib\site-packages\requests\sessions.py", line 533, in request
    resp = self.send(prep, **send_kwargs)
  File "C:\Users\zuimojun\AppData\Local\Programs\Python\Python37\lib\site-packages\requests\sessions.py", line 646, in send
    r = adapter.send(request, **kwargs)
  File "C:\Users\zuimojun\AppData\Local\Programs\Python\Python37\lib\site-packages\requests\adapters.py", line 449, in send
    timeout=timeout
  File "C:\Users\zuimojun\AppData\Local\Programs\Python\Python37\lib\site-packages\urllib3\connectionpool.py", line 672, in urlopen
    chunked=chunked,
  File "C:\Users\zuimojun\AppData\Local\Programs\Python\Python37\lib\site-packages\urllib3\connectionpool.py", line 387, in _make_request
    conn.request(method, url, **httplib_request_kw)
  File "C:\Users\zuimojun\AppData\Local\Programs\Python\Python37\lib\http\client.py", line 1229, in request
    self._send_request(method, url, body, headers, encode_chunked)
  File "C:\Users\zuimojun\AppData\Local\Programs\Python\Python37\lib\http\client.py", line 1274, in _send_request
    body = _encode(body, 'body')
  File "C:\Users\zuimojun\AppData\Local\Programs\Python\Python37\lib\http\client.py", line 160, in _encode
    (name.title(), data[err.start:err.end], name)) from None
UnicodeEncodeError: 'latin-1' codec can't encode character '\u86c7' in position 8: Body ('蛇') is not valid Latin-1. Use body.encode('utf-8') if you want to send it encoded in UTF-8.






#### 解决方法:
  .encode("utf-8").decode("latin1")        在发生编码错误的地方使用这个即可    
我的是在params参数时发证编码错误的,所以要在params或者data值后面添加。
posted @ 2021-06-07 21:42  醉魔君  阅读(627)  评论(0编辑  收藏  举报