2016-08-17 94 views
0

簡短版本: 此Python請求不起作用。 Javascript版本的確。爲什麼?爲什麼Python請求庫不能複製這個Ajax調用?

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() 

加長版: 我有此Javascript,成功地使一個Ajax調用。我向控制檯打印響應,並可以從我發送的輸入中看到一系列建議字符。

​​

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:假}]]]

現在我正在努力在Python中複製。我試過使用上面的代碼和它的許多變體,但每次我收到響應'FAILED_TO_PARSE_REQUEST_BODY'。 Ajax和Python調用之間有什麼不同,導致我的請求失敗?

這個問題類似於thisthis,但它們涉及多次使用相同的密鑰和不正確的數據編碼,我不認爲這適用於這種情況。

回答

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() 
相關問題