python爬虫04--有道翻译

时间:2021-02-10 16:37:48
import urllib.request
import urllib.parse
import json
url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=null'
#定义一个字典
input_data =input("请输入您要翻译的语句:")
data = {}
data['type'] = 'AUTO'
data['i'] = input_data
data['doctype'] = 'json'
data['xmlVersion'] = '1.8'
data['keyfrom'] = 'fanyi.web'
data['ue'] = 'UTF-8'
data['action'] = 'FY_BY_CLICKBUTTON'
data['typoResult'] = 'true'
#data urlencode 硬编码为utf-8的编码
data = urllib.parse.urlencode(data).encode("utf-8")
#请求
request = urllib.request.urlopen(url,data)
#读取文本解码
data = request.read().decode("utf-8")
print(data)
print('###################################')
string = json.loads(data)
print(string)
print('##################################')
tra = string['translateResult'][0][0]['tgt']
print("您输入的是:" + input_data + " 翻译为:" + tra)