Call Google Translate from Python

I want to execute this script (view source) that uses the AJAX API to translate Google from python and can pass arguments and get a response. I don't care about HTML.

I understand that I need to implement a Javascript interpreter. Does this mean that I need to have a browser instance and manipulate it? What is the cleanest way to access this API from python?

+4
source share
3 answers

You can use google-api-translate-python to talk with google api.

EDIT: It is not clear where the sources are found here .

+3
source

Instead, you can use the RESTful API. It is intended for environments that are not Javascript.

http://code.google.com/apis/ajaxlanguage/documentation/reference.html#_intro_fonje

This should be easy to use from Python.

+3
source

I had to do this recently, and since I had to translate long lines, I could not use the URL parameters, but rather used a data payload. Thought it was the best place to share this solution.
The trick is basically to use Python's excellent Requests post, but since Google requires a GET request, use the "X-HTTP-Method-Override" header to override the request method for GET.
(explicitly using request.get loads the data payload)

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 who is still doing this.

+1
source

All Articles