Python3 uses the urllib example to retrieve googletranslate (Google translate)

Source: Internet
Author: User
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 "))

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.