简短版本 此Python请求不起作用。 Javascript版本。为什么?
import json
import requests
url = 'https://inputtools.google.com/request?itc=ja-t-i0-handwrit&app=demopage'
data = '{"app_version":0.4,"api_level":"537.36","device":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36","input_type":0,"options":"enable_pre_space","requests":[{"writing_guide":{"writing_area_width":200,"writing_area_height":200},"pre_context":"","max_num_results":1,"max_completions":0,"ink":[[[100,100],[20,180],[0,1]],[[20,180],[100,100],[2,3]]]}]}'
headers = {'content-type': 'application/json'}
r = requests.post(url, json=data, headers=headers)
print r.json()
更长的版本: 我有这个成功进行Ajax调用的Javascript。我将响应打印到控制台,可以看到我发送的输入中的一系列建议字符。
https://jsbin.com/wufesifasa/1/edit?js,console,output
var text = {
'app_version' : 0.4,
'api_level' : '537.36',
'device' : window.navigator.userAgent,
'input_type' : 0, // ?
'options' : 'enable_pre_space', // ?
'requests' : [ {
'writing_guide' : {
'writing_area_width' : 200, // canvas width
'writing_area_height' : 200, // canvas height
},
'pre_context' : '', // confirmed preceding chars
'max_num_results' : 1,
'max_completions' : 0,
'ink' : []
} ]
};
// written coordinates to be sent
text.requests[0].ink = [
[[100,100],[20,180],[0,1]],
[[20,180],[100,100],[2,3]],
];
console.log(JSON.stringify(text))
$.ajax({
url : 'https://inputtools.google.com/request?itc=ja-t-i0-handwrit&app=demopage',
method : 'POST',
contentType : 'application/json',
data : JSON.stringify(text),
dataType : 'json',
}).done(function(json) {
console.log(json);
});
输出:
[“SUCCESS”,[[“fb02254b519a9da2”,[“+”,“十”,“t”,“T”,“ナ”,“f”,“子”, “干”,“1”,“千”,[],[对象] {is_html_escaped:false}]]]
现在我正试图在Python中复制它。我已尝试使用上面的代码及其中的许多变体,但每次收到响应'FAILED_TO_PARSE_REQUEST_BODY'时。使我的请求失败的Ajax和Python调用之间有什么不同?
答案 0 :(得分:0)
行json=data
应该是data=data
。 json属性接受字典,data
字符串不是。以下是工作代码的样子:
import json
import requests
url = 'https://inputtools.google.com/request?itc=ja-t-i0-handwrit&app=demopage'
data = '{"app_version":0.4,"api_level":"537.36","device":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36","input_type":0,"options":"enable_pre_space","requests":[{"writing_guide":{"writing_area_width":200,"writing_area_height":200},"pre_context":"","max_num_results":1,"max_completions":0,"ink":[[[100,100],[20,180],[0,1]],[[20,180],[100,100],[2,3]]]}]}'
headers = {'content-type': 'application/json'}
r = requests.post(url, json=data, headers=headers)
print r.json()
答案 1 :(得分:0)
信誉不足,无法发表评论,但雷(Ray)正确地说,尽管发布的代码仍然显示'json = data',而不是'data = data'。我运行了代码,并得到了OP正在寻找的匹配响应,尽管我只是打印了r.content
`b'["SUCCESS",[["fb02254b519a9da2",["\xe5\x8d\x81","+","t","\xef\xbc\x8b","f","\xe3\x83\x8a","1","\xe3\x83\x88","\xe5\x8d\x9c","\xe5\xa3\xab"],[],{"is_html_escaped":false}]]]'`