此博文用网络爬虫的方法将有道翻译的信息抓取到,具体代码如下:
import urllib.request
import urllib.parse
import json
import time
#延迟
while True:
content = input('请输入需要翻译的内容(输入"q!"退出程序):')
if content == 'q!':
break
url = ('http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=null')
#head = {}
#head['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36'
#隐藏方法一
data = {}
data['typr'] = 'AUTO'
data['i'] = content
data['doctype'] = 'json'
data['xmlVersion'] = '1.8'
data['keyfrom'] = 'fanyi.web'
data['ue'] = 'UTF-8'
data['action'] = 'FY_BY_CLICKBUTTON'
data['typoResult'] = 'true'
data = urllib.parse.urlencode(data).encode('utf-8')
req = urllib.request.Request(url, data)
req.add_header('User-Agent','Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36')
#隐藏方法二
response = urllib.request.urlopen(url ,data)
html = response.read().decode('utf-8')
target = json.loads(html)
print("翻译的结果:%s"%(target['translateResult'][0][0]['tgt']))
time.sleep(1)
具体显示如下:
希望大家可以喜欢~