This article describes how to use urllib to retrieve googletranslate (Google translate,
The code is as follows:
#! /Usr/bin/env python3
#-*-Coding: UTF-8 -*-
# File Name: gt1.py
# Purpose:
# Creation Date: 1390366260
# Last Modified: Wed 22 Jan 2014 06:14:11 PM CST
# Release By: Doom. zhou
Import urllib. request
Import sys
Typ = sys. getfilesystemencoding ()
Def translate (querystr, to_l = "zh", from_l = "en "):
''' For google tranlate by doom
'''
C_agent = {'user-Agent': "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.165063 Safari/537.36 AppEngine-Google ."}
Flag = 'class = "t0">'
Tarurl = "http://translate.google.com/m? Hl = % s & sl = % s & q = % s \
"% (To_l, from_l, querystr. replace (" "," + "))
Request = urllib. request. Request (tarurl, headers = C_agent)
Page = str (urllib. request. urlopen (request). read (). decode (typ ))
Target = page [page. find (flag) + len (flag):]
Target = target. split ("<") [0]
Return target
Print (translate ("Hello world "))