2013年5月26日 星期日

The Free Translate API from Google

   The google translate api is not free in v2. but some way(hack) let it's work. we can sniff the Google Translate. and mimic the request, the example show as follow:

main.py
TRANSLATE_URL_PREFIX='http://translate.google.com.tw/translate_a/t?client=t&hl=zh-TW&sl=en&tl=zh-TW&ie=UTF-8&oe=UTF-8&multires=1&prev=enter&ssel=0&tsel=0&sc=1&q='
# the user agent is neccerry ...
query = "THE WORDS YOU WANT TO TRANSLATE"
user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.93 Safari/537.36'
headers = { 'User-Agent' : user_agent }
req = urllib2.Request(self.TRANSLATE_URL_PREFIX+query), None, headers)
res = urllib2.urlopen(req)
r = res.read()
while ',,' in r:
    r = r.replace(',,',',')
content = json.loads(r)
result = content[0][0][0]) 

The most trick is the response JSON is invalid. we should remove the wied tag : ",,".

hope it's help for you :)

沒有留言:

張貼留言