# !/usr/bin/python # -*- encoding: UTF-8 -*- import urllib import urllib2 headers={"X-Requested-With":"XMLHttpRequest", "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36", "Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"}#也可以使用代理headers={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36"} url="http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule" print u"请输入需要翻译的文字:", key=raw_input()#外部输入的key是简体中文格式(gb2312的编码) fromdata={"from":"AUTO", "to":"AUTO", "i":key.decode("gb2312"),#把gb2312编码格式的key解码成这个程序可以识别的unicode格式(包含utf-8格式) "doctype":"json", "version":"2.1", "keyfrom":"fanyi.web", "action":"FY_BY_CLICKBUTTION", "typoResult":"true"} data = urllib.urlencode(fromdata) request=urllib2.Request(url,data) response = urllib2.urlopen(request) html = response.read() print html.encode("gb2312")#把这个程序跑出来的程序(unicode格式)打印到终端上,终端是cmd是识别简体中文(gb2312编码),所以把结果编码成gb2312格式的,这样中文的结果才能显示出来 结果打印的是json格式的 结果是: {"type":"FR2ZH_CN","errorCode":0,"elapsedTime":34,"translateResult":[[{"src":"??python","tgt":"? ?巨蟒"}]]} 在json在线解析器http://www.json.cn/中显示出来的是: { "type":"FR2ZH_CN", "errorCode":0, "elapsedTime":34, "translateResult":[ [ { "src":"??python", "tgt":"? ?巨蟒" } ] ] } 如果是出现{"errorCode":50}这是因为访问的链接需要密码 只要把07.url = 'http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule&sessionFrom=null'中translate_o?后面的“_o”去掉就好了,其他比如时间戳什么的都不用改。其他的URL也是一样,去掉“_o”就好
爬虫-有道翻译
最新推荐文章于 2024-04-18 11:22:38 发布