Skip to content

Instantly share code, notes, and snippets.

@PandyYang
Created February 21, 2018 02:55
Show Gist options
  • Save PandyYang/e11f5e062da0a73fe2617d70fa71891c to your computer and use it in GitHub Desktop.
Save PandyYang/e11f5e062da0a73fe2617d70fa71891c to your computer and use it in GitHub Desktop.
import urllib.request
import urllib.parse
import json
import time
import random
while True:
content = input("请输入需要翻译的内容(输入q!,退出程序):")
if content== "q!" :
break
url = "http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule"
head = {}#用字典添加头文件
head['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.221 Safari/537.36 SE 2.X MetaSr 1.0'
date = {}
date['i'] = content
date['from'] = 'AUTO'
date['to'] = 'AUTO'
date['smartresult'] = 'dict'
date['client'] = 'fanyideskweb'
date['salt'] = '1519104430302'
date['sign'] = 'fe82320471ae1da79b20686852929526'
date['doctype'] = 'json'
date['version'] = '2.1'
date['keyfrom'] = 'fanyi.web'
date['action'] = 'FY_BY_REALTIME'
date['typoResult'] = 'false'
date = urllib.parse.urlencode(date).encode('utf-8')
#方法2:动态添加浏览信息头文件
# req = urllib.request.Request(url,date)
# req.add_header('User-agent','Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.221 Safari/537.36 SE 2.X MetaSr 1.0')
#url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'
# iplist = ['118.91.163.142:80', '59.153.17.58:80', '154.73.28.35:80']
# proxy_support = urllib.request.ProxyHandler({"http": random.choice(iplist)})
# opener = urllib.request.build_opener(proxy_support)
# opener.addheaders = [('User-Agent',
# 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.221 Safari/537.36 SE 2.X MetaSr 1.0')]
# urllib.request.install_opener(opener)
# response = urllib.request.urlopen(url)
# html = response.read().decode('utf-8')
response = urllib.request.urlopen(url,date)
html = response.read().decode('utf-8')
#print(html)
target = json.loads(html)
print("翻译的结果为:%s" %(target['translateResult'][0][0]['tgt']))
time.sleep(5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment