python爬取有道翻译

1.有道翻译的请求参数
salt,sign和ts须动态设置

# http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule
# i: tree
# from: AUTO
# to: AUTO
# smartresult: dict
# client: fanyideskweb
# salt: 15557340553352  >>>>>>>>>>>i = r + parseInt(10 * Math.random(), 10);
# sign: 3c0a7be86a7e5d75d45d7a25df6f8259  >>>>>>>>>>n.md5("fanyideskweb" + e + i + "@6f#X3=cCuncYssPsuRUE")
# ts: 1555734055335    >>>>>>>>>>>r = "" + (new Date).getTime()
# bv: f8c295588ce195d0453511f751132244
# doctype: json
# version: 2.1
# keyfrom: fanyi.web
# action: FY_BY_REALTlME
import requests, time, hashlib, random, json

# 请求地址和请求头
url = 'http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'
headers = {
    'Accept': 'application/json, text/javascript, */*; q=0.01',
    'Accept-Encoding': 'gzip, deflate',
    'Accept-Language': 'zh-CN,zh;q=0.9',
    'Connection': 'keep-alive',
    'Content-Length': '239',
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    'Cookie': 'OUTFOX_SEARCH_USER_ID=-819738210@10.169.0.83; OUTFOX_SEARCH_USER_ID_NCOO=1606744505.8724139; DICT_UGC=be3af0da19b5c5e6aa4e17bd8d90b28a|; JSESSIONID=abcTTc7n1DBzJ63Dw_4Ow; _ntes_nnid=04359c568b1008fcef153722370d20df,1555734032084; ___rl__test__cookies=1555739165615',
    'Host': 'fanyi.youdao.com',
    'Origin': 'http://fanyi.youdao.com',
    'Referer': 'http://fanyi.youdao.com/?keyfrom=dict2.top',
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36',
    'X-Requested-With': 'XMLHttpRequest',
    }

word = input('请输入要翻译的内容:')
# 通过是否有空格判断是句子还是单词
flag = word.find(' ')

ts = str(int(time.time() * 1000))
salt = str(ts) + str(random.randint(0,10))
md5 = hashlib.md5()
md5.update(("fanyideskweb" + word + salt + "@6f#X3=cCuncYssPsuRUE").encode())
sign = md5.hexdigest()

data = {
    'i': word,
    'salt': salt,
    'sign': sign,
    'ts': ts,
    'from': 'AUTO',
    'to': 'AUTO',
    'smartresult': 'dict',
    'client': 'fanyideskweb', 
    'bv': 'f8c295588ce195d0453511f751132244',
    'doctype': 'json',
    'version': '2.1',
    'keyfrom': 'fanyi.web',
    'action': 'FY_BY_REALTlME',
}

res = requests.post(url,data=data,headers=headers)
res.encoding = 'utf-8'
html = res.text
d = json.loads(html)
print(d)

print(word,'的解释为:',d["translateResult"][0][0]['tgt'])
if flag == -1:
    try:
        print(''.join(d['smartResult']['entries']),end='')
    except:
        pass
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值