我正在尝试从LeetCode-CN获取所有提交的代码,我需要获取问题的翻译。卷曲命令可以给我想要的结果:
curl 'https://leetcode-cn.com/graphql' -H 'authority: leetcode-cn.com' -H 'origin: https://leetcode-cn.com' -H 'content-type: application/json' -H 'referer: https://leetcode-cn.com/problemset/all/' --data '{"operationName":"getQuestionTranslation","variables":{},"query":"query getQuestionTranslation($lang: String) {\n translations: allAppliedQuestionTranslations(lang: $lang) {\n title\n questionId\n __typename\n }\n}\n"}'
但是以下python代码无法正常工作:
def loadChnProblemList(client):
query = {
"operationName": "getQuestionTranslation",
"variables": {},
"query": "query getQuestionTranslation($lang: String) {\n translations: allAppliedQuestionTranslations(lang: $lang) {\n title\n questionId\n __typename\n }\n}\n"}
headers = {
"content-type": "application-json",
"origin": "https://leetcode-cn.com",
"referer": "https://leetcode-cn.com/problemset/all/"
}
response = requests.post("https://leetcode-cn.com/graphql", headers=headers, data=json.dumps(query))
data = json.loads(response.text)
print(data)
服务器将响应:
{"errors":[{"message":"Must provide query string."}]}'
为什么curl命令起作用但python代码不起作用?
Shijith是正确的-修复了将内容类型更改为application / json的问题。有关更多详细信息,请参见requests docs。