http://blog.csdn.net/nunchakushuang/article/details/75294947
因为有道翻译有反爬虫机制,所以简单的爬肯定不行,但是这一篇博客只是告诉我们有道的JS反爬虫代码,完全运行后还需要改你得到的POST请求的URL
我的URL:http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule {"errorcode":50}
需要修改 http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule
就是把_o去掉,而且这样的请求只能是用于英文翻译汉文.
为避免{"errorCode":50}的错误,去除 url 中的_o
代码:
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
import json
import requests
#有道api
def translation(word):
url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'
#word 为需要翻译的词
data={
'i':word,
'form':'AUTO',
'to':'Auto',
'doctype':'json',
'version':'2.1',
'keyfrom':'fanyi.web',
'action':'FY_BY_CLICKBUTTON',
'typoResult':'false'
}
response = requests.post(url,data=data)
if response.status_code == 200:
return response.text
else:
print("error please try again")
def get_result(response):
result = json.loads(response)
print(result)
print("输入的词为:%s" % result['translateResult'][0][0]['src'])
print("输入的词为:%s" % result['translateResult'][0][0]['tgt'])
def main():
word = input("请输入需要翻译的词或语句:")
translate = translation(word)
get_result(translate)
main()