Python爬虫|调用有道翻译的简单操作

python版本:3.6.0

工具:urllib模块或者requests模块

参考链接:

http://www.jianshu.com/p/e45511bcd001

http://fanyi.youdao.com/

http://tool.chinaz.com/Tools/unixtime.aspx

下面附代码:

利用urllib模块


#!/user/bin/env python3
# -*- coding:utf-8 -*-
#time: 2017/07/04
#version: 1.0

import urllib.request
import urllib.parse
import json
import time
import hashlib

while True:
content = input('请输入要翻译的内容(输入"q!推出程序"):')
if content =='q!':
break
m = hashlib.md5()
d = content
u = 'fanyideskweb'
f = str(int(time.time()*1000))#当前时间戳
c = "rY0D^0'nM0}g5Mm1z%1G4"
m.update((u + d + f + c).encode('utf-8'))
data= {
'i':d,
'from':'AUTO',
'to':'AUTO',
'smartresult':'dict',
'client':u,
'salt':f,
'sign':m.hexdigest(),
'doctype':'json',
'version':'2.1',
'keyfrom':'fanyi.web',
'action':'FY_BY_ENTER',
'typoResult':'true'
}
url = 'http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule&sessionFrom=null'
headers = {
'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36'

}

data = urllib.parse.urlencode(data).encode('utf-8')
req = urllib.request.Request(url,data,headers)
response = urllib.request.urlopen(req)
html = response.read().decode('utf-8')

target = json.loads(html)

#print(data)
#print(response)
#print(html)
print("翻译结果:%s" % (target['translateResult'][0][0]['tgt']))
time.sleep(0.5)

利用requests模块


import requests
import time
import hashlib

#content = input("请输入需要翻译的内容:")

if __name__== "__main__":
m = hashlib.md5()
d = content
u = 'fanyideskweb'
f = str(int(time.time()*1000))
c = "rY0D^0'nM0}g5Mm1z%1G4"
m.update((u + d + f + c).encode('utf-8'))
data= {
'i':d,
'from':'AUTO',
'to':'AUTO',
'smartresult':'dict',
'client':u,
'salt':f,
'sign':m.hexdigest(),
'doctype':'json',
'version':'2.1',
'keyfrom':'fanyi.web',
'action':'FY_BY_ENTER',
'typoResult':'true'
}
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36',
'Origin':'http://fanyi.youdao.com/',
'Referer':'http://fanyi.youdao.com/',
}
#print(data)
post_url = 'http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule&sessionFrom=null'
youdaojson = requests.post(post_url,headers = headers,data=data).json()
#print(youdaojson)
#print("翻译结果:%s" % (youdaojson['translateResult'][0][0]['tgt']))

分享