在做接口自动化框架开发时,遇到调用requests.post方法的时候报错。
报错信息:
请求出错了'latin-1' codec can't encode characters in position 9-10: 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 "D:/PythonStudyDemo/API_AUTO/run.py", line 11, in
run(test_data)
File "D:/PythonStudyDemo/API_AUTO/run.py", line 7, in run
res=HttpRequest().http_request(item["url"],item["data"],item[' http_method'])
File "D:\PythonStudyDemo\API_AUTO\tools\http_request.py", line 14, in http_request
raise e
File "D:\PythonStudyDemo\API_AUTO\tools\http_request.py", line 9, in http_request
res = requests.post(url,data,cookies=cookie)
File "C:\Users\32465\AppData\Local\Programs\Python\Python37-32\lib\site-packages\requests\api.py", line 119, in post
return request('post', url, data=data, json=json, **kwargs)
File "C:\Users\32465\AppData\Local\Programs\Python\Python37-32\lib\site-packages\requests\api.py", line 61, in request
return session.request(method=method, url=url, **kwargs)
File "C:\Users\32465\AppData\Local\Programs\Python\Python37-32\lib\site-packages\requests\sessions.py", line 530, in request
resp = self.send(prep, **send_kwargs)
File "C:\Users\32465\AppData\Local\Programs\Python\Python37-32\lib\site-packages\requests\sessions.py", line 643, in send
r = adapter.send(request, **kwargs)
File "C:\Users\32465\AppData\Local\Programs\Python\Python37-32\lib\site-packages\requests\adapters.py", line 449, in send
timeout=timeout
File "C:\Users\32465\AppData\Local\Programs\Python\Python37-32\lib\site-packages\urllib3\connectionpool.py", line 672, in urlopen
chunked=chunked,
File "C:\Users\32465\AppData\Local\Programs\Python\Python37-32\lib\site-packages\urllib3\connectionpool.py", line 387, in _make_request
conn.request(method, url, **httplib_request_kw)
File "C:\Users\32465\AppData\Local\Programs\Python\Python37-32\lib\http\client.py", line 1229, in request
self._send_request(method, url, body, headers, encode_chunked)
File "C:\Users\32465\AppData\Local\Programs\Python\Python37-32\lib\http\client.py", line 1274, in _send_request
body = _encode(body, 'body')
File "C:\Users\32465\AppData\Local\Programs\Python\Python37-32\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 characters in position 9-10: Body ('上海') is not valid Latin-1. Use body.encode('utf-8') if you want to send it encoded in UTF-8.
出错代码:
requests.get(url,data,cookies=cookie)
主要原因是 请求body里面有 汉字,没有进行untf-8编码导致,解决方法,对data进行 encode()编码 即可:
requests.get(url,data.encode(),cookies=cookie)
修改报错问题解决!