利用Python爬虫实现有道翻译的功能
# requests POST 方法 实战:有道翻译
import requests,json
import time,random,hashlib
# import UserAgent
name = input('请输入要查询的单词: ')
now_time = time.time() * 1000
sj = str(random.randint(1,9))
salt = str(int(now_time)) + sj
str_ = "fanyideskweb" + name + sj + "Tbh5E8=q6U3EXe+&L[4c@"
md = hashlib.md5()
md.update(str_.encode())
md5_str = md.hexdigest()
data = {
'i': name,
'from': 'AUTO',
'to': 'AUTO',
'smartresult': 'dict',
'client': 'fanyideskweb',
# 以下三个参数可以写死,可以动态生成
# 'salt':'16089682965572',
# 'sign': 'd04dec04f67754e34400a94e23e2acd5',
# 'lts': '1608968296557',
'salt':salt,
'sign':md5_str,
'lts': now_time,
'bv': '51bf9b9449c1ea0d9b6e31aea82899bb',
'doctype': 'json',
'version': '2.1',
'keyfrom': 'fanyi.web',
'action': 'FY_BY_REALTlME'
}
res = requests.post(url='http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule',
data=data,headers={'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0) Gecko/20100101 Firefox/6.0'})
t = res.content.decode('utf8')
# 把返回来的json字符串解析成字典
result_dict = json.loads(t)
# 获取翻译结果
print(result_dict)
ans=result_dict['translateResult'][0][0]['tgt']
print('翻译的结果是:',ans)