# -*- coding: utf-8 -*- #模拟有道翻译 import urllib import urllib2 #通过抓包得到的url地址 url="http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule " #完整的headers headers={ #"Host":"fanyi.youdao.com", "User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64; rv:65.0) Gecko/20100101 Firefox/65.0", "Accept":"application/json, text/javascript, */*; q=0.01", "Accept-Language":"zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2", "Content-Type":"application/x-www-form-urlencoded; charset=UTF-8", "X-Requested-With":"XMLHttpRequest", #"Connection":"keep-alive" } #输入关键字 只能英译中 kkk~ key=raw_input("请输入需要翻译的文字:") #发送到web服务器的表单数据 formdata={ "type":"AUTO", "i":key, "doctype" :"json", "version" : "2.1", "keyfrom" : "fanyi.web", "ue":"UTF-8", "action" : "FY_BY_REALTIME", "typoResult" : "true" } #转码 data=urllib.urlencode(formdata) #请求 Request()方法里有值请求为POST 没有则为GET request=urllib2.Request(url,data=data ,headers=headers) reponse=urllib2.urlopen(request) print reponse.read()
12345678910111213141516171819202122232425262728293031323334353637但是这个方法只能英译中
其原因应该是"type":"EN2ZH_CN"代表英2中 这个type找不到哪里修改
代码曾遇到的问题
1.{"errorcode":50}
解决方法url="http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule "将translate_o里的_o去掉变为url="http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule "即可
2.urllib2.HTTPError: HTTP Error 502: Bad Gateway
解决方法把传到数据单的typoResult标签置为true"typoResult" : "true"
所有有关网页的信息都是用fliddler抓包抓下来的分析了RAW WebForms,查看了JSON
运行结果
请输入需要翻译的文字:peace {"type":"EN2ZH_CN","errorCode":0,"elapsedTime":0,"translateResult":[[{"src":"peace","tgt":"和平"}]]} 123