import urllib.request
import urllib.parse
import json
import time
while True:
content = input("请输入要翻译的内容(输入q退出程序):")
if content == 'q':
break
# F12看翻译的时候fanyi.youdao.com的network的url和formdata,注意去掉url中的_o
url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'
"""
第一种方法是这么加head
head = {}
head['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.62 Safari/537.36'
同时下面的
reponse = urllib.request.urlopen(url, data)改为
reponse = urllib.request.urlopen(url, data,head)
"""
data = {}
data['i'] = content
data['from'] = 'AUTO'
data['to'] = 'AUTO'
data['smartresult'] = 'dict'
data['client'] = 'fanyideskweb'
data['salt'] = '1541337836975'
data['sign'] = '9dc6accc337e0d317448d7e594993794'
data['doctype'] = 'json'
data['version'] = '2.1'
data['keyfrom'] = 'fanyi.web'
data['action'] = 'FY_BY_CLICKBUTTION'
data['typoResult'] = 'false'
data = urllib.parse.urlencode(data).encode('utf-8')
# 第二种方法是先 生成对象,再追加header,add_header
req = urllib.request.Request(url, data)
req.add_header('User-Agent',
'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.62 Safari/537.36')
reponse = urllib.request.urlopen(url, data)
html = reponse.read().decode('utf-8')
target = json.loads(html)
print(target['translateResult'][0][0]['tgt'])
# time.sleep(5)每隔五秒再次启动翻译,防止网站屏蔽本IP