我可是写了半天时间,不断来回折腾最后搞定了,代码如下
import urllib.request
import urllib.parse
import json
c = input(“请输入需要翻译的内容:”)
url = ‘http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule’
data = {}
data[‘i’] = c
data[‘from’] = ‘AUTO’
data[‘to’] = ‘AUTO’
data[‘smartresult’] = ‘dict’
data[‘client’] = ‘fanyideskweb’
data[‘salt’] = ‘15464242969552’
data[‘sign’] = ‘9b0e4a9ea0d9bb3e4537667f17cd37ad’
data[‘ts’] = ‘1546424296955’
data[‘bv’] = ‘e2a78ed30c66e16a857c5b6486a1d326’
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’)
response = urllib.request.urlopen(url,data)
html = response.read().decode(‘utf-8’)
targrt = json.loads(html)
print(“翻译结果:%s” %(targrt[‘translateResult’][0][0][‘tgt’]))
和原来略有不同的是有道的URL复制下来后需要删除_o这两个字符就可以了
然后很多人浏览器不同,可能找不到POST的表单,我建议你下个火狐浏览器然后打开有道翻译,接着右键查看元素,接着在翻译框框输入任意东西翻译,你会看到这样
然后点击网络一栏你就看到POST了,接着右边的消息头下的请求网址就是URL了
别忘了复制后删除_o不然爬不到
表单数据在右边的参数一栏里面
最后复制上去填入DATA就行啦