Reputation: 21801
I want to execute this script (view source) that uses Google Translate AJAX API from python, and be able to pass arguments and get the answer back. I don't care about the HTML.
I understand I need to embed a Javascript interpreter of some sort. Does this mean I need to have a browser instance and manipulate it? What is the cleanest way to access this API from python?
Upvotes: 4
Views: 2973
Reputation: 688
Had to do this recently, and since I had to translate long strings, I couldn't use URL parameters, but rather use a data payload. Thought this is the best place to share this solution.
The trick basically is to use Python's excellent Requests module post, but since google require a GET request, use the 'X-HTTP-Method-Override' header to override the request method to GET.
(plainly using requests.get messes up the data payload)
the code:
import requests
def translate_es_to_en(text):
url = "https://www.googleapis.com/language/translate/v2"
data = {
'key': '<your-server-google-api-key>'
'source': 'es',
'target': 'en',
'q': text
}
headers = {'X-HTTP-Method-Override': 'GET'}
response = requests.post(url, data=data, headers=headers)
return response.json()
Hope this helps anyone still tackling this
Upvotes: 1
Reputation: 5480
You can use google-api-translate-python to talk to google api.
EDIT: It wasn't clear where the sources are, found them here.
Upvotes: 3
Reputation: 172249
You can use the RESTful API instead. It's designed for environments that are not Javascript.
http://code.google.com/apis/ajaxlanguage/documentation/reference.html#_intro_fonje
That should be easy to use from Python.
Upvotes: 3