首页 > 解决方案 > python请求发布返回奇怪的字符

问题描述

我正在尝试将发布请求发送到应该返回 json 的 api 端点。但是我得到了奇怪的字符。我尝试使用 utf-8 进行编码,但没有成功。

import requests

url1= "https://cliff.mediacloud.org/process"

header ={"accept": "application/json, text/javascript, */*; q=0.01",
"accept-encoding": "gzip, deflate, br",
"accept-language": "en-US,en;q=0.9,fr-DZ;q=0.8,fr;q=0.7",
"content-length": "56",
"content-type": "application/x-www-form-urlencoded; charset=UTF-8",
"cookie": "__cfduid=d90785d2f72bf656c19e794239e26185d1585929126; _ga=GA1.2.1927368988.1585929126; _gid=GA1.2.61609766.1585929126 ; _gat_gtag_UA_60744513_13=1",
"origin": "https://cliff.mediacloud.org",
"referer": "https://cliff.mediacloud.org/",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin",
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36",
"x-requested-with": "XMLHttpRequest"}

text1 = "i am traveling to france"

data1={"text": text1,
"demonyms": "false",
"language": "EN"}

r = requests.post(url=url1, headers=header, data=data1 )

print (r.text)

关于如何解决这个问题的任何线索?

标签: pythonpython-3.xencodingpython-requests

解决方案


去掉accept-encoding中的br

"accept-encoding": "gzip, deflate",

请求结果将如下所示

{"milliseconds": 3, "language": "EN", "version": "2.6.1", "results": {"places": {"mentions": [{"featureCode": "PCLI", "featureClass": "A", "confidence": 1.0, "lon": 2.0, "countryGeoNameId": "3017382", "source": {"charIndex": 18, "string": "france"}, "population": 64768389, "stateGeoNameId": "", "countryCode": "FR", "name": "Republic of France", "stateCode": "00", "id": 3017382, "lat": 46.0}], "focus": {"cities": [], "countries": [{"score": 1, "featureCode": "PCLI", "stateGeoNameId": "", "featureClass": "A", "countryCode": "FR", "name": "Republic of France", "lon": 2.0, "countryGeoNameId": "3017382", "stateCode": "00", "id": 3017382, "lat": 46.0, "population": 64768389}], "states": []}}, "organizations": [], "people": []}, "status": "ok"}

推荐阅读