python3使用urllib示例取googletranslate(谷歌翻译)
程序员文章站
2022-04-19 09:09:41
复制代码 代码如下:#!/usr/bin/env python3# -*- coding: utf-8 -*-# file name : gt1.py# purpose :...
复制代码 代码如下:
#!/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"))