python3使用urllib示例取googletranslate(谷歌翻译)

yipeiwu_com6年前Python基础

复制代码 代码如下:

#!/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"))

相关文章

Python实现自定义函数的5种常见形式分析

本文实例讲述了Python自定义函数的5种常见形式。分享给大家供大家参考,具体如下: Python自定义函数是以def开头,空一格之后是这个自定义函数的名称,名称后面是一对括号,括号里放...

Python的Django中将文件上传至七牛云存储的代码分享

最近在写的一个django小项目需要实现用户上传图片的功能,使用到了七牛云存储,特此记录下来。这里我使用的七牛python SDK 版本是7.0.3,函数使用上可能会与旧版有些不同。 原...

python解析基于xml格式的日志文件

python解析基于xml格式的日志文件

大家中午好,由于过年一直还没回到状态,好久没分享一波小知识了,今天,继续给大家分享一波Python解析日志的小脚本。 首先,同样的先看看日志是个啥样。 都是xml格式的,是不是看着就头...

Python模块_PyLibTiff读取tif文件的实例

Usage example (libtiff wrapper) from libtiff import TIFF # to open a tiff file for reading:...

Python字典的核心底层原理讲解

Python字典的核心底层原理讲解

字典对象的核心是散列表。散列表是一个稀疏数组(总是有空白元素的数组),数组的每个单元叫做 bucket。每个 bucket 有两部分:一个是键对象的引用,一个是值对象的引用。所有 buc...