首先要用到hashlib模块来计算遇到的md5加密问题
# coding:utf-8
import hashlib
data = 'python'
# 创建hash对象
md5 = hashlib.md5()
# 向hash对象中添加需要做hash运算的字符串
md5.update(data.encode())
# 获取字符串的hash值 hexdigest 16进制
result = md5.hexdigest()
print(result)
上源码哈
#coding:utf-8
import requests
import hashlib
import time
import random
import json
class Youdao(object):
def __init__(self,word):
self.url = 'https://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'
self.headers ={
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36',
'Cookie': 'OUTFOX_SEARCH_USER_ID=284317034@10.169.0.81; JSESSIONID=aaafNS_X9rEJLgmojgj2x; OUTFOX_SEARCH_USER_ID_NCOO=1207360466.0357785; ___rl__test__cookies=1638682669421',
'Referer': 'https://fanyi.youdao.com/'
}
self.formdata = None
self.word = word
def generate_formdata(self):
'''
ts: r = "" + (new Date).getTime(),
salt: ts + parseInt(10 * Math.random(), 10);
sign: n.md5("fanyideskweb" + e + i + "Y2FYu%TNSbMCxc3t2u^XT")
'''
ts = str(int(time.time()*1000))
salt = ts + str(random.randint(0,9))
tempstr = "fanyideskweb" + self.word + salt + "Y2FYu%TNSbMCxc3t2u^XT"
md5 = hashlib.md5()
md5.update(tempstr.encode())
sign = md5.hexdigest()
self.formdata = {
"i": self.word,
"from": "AUTO",
"to": "AUTO",
"smartresult": "dict",
"client": "fanyideskweb",
"salt": salt,
"sign": sign,
"lts": ts,
"bv": "36756d23dc251cc14bf9558b9730e3a5",
"doctype": "json",
"version": "2.1",
"keyfrom": "fanyi.web",
"action": "FY_BY_REALTlME"
}
def get_data(self):
response = requests.post(self.url,data=self.formdata,headers=self.headers)
return response.content
def run(self):
# 爬虫思路
# url
# headers
# formdata
self.generate_formdata()
# 发送请求, 获取响应, 解析数据
data = self.get_data()
# print(data)
js = json.loads(data)
# print(js.get('translateResult'))
# 遍历字典列表
# for value in js.values():
# print(value)
for dict in js.get('translateResult'):
pass
# print(dict)
for value in dict[0].values():
print(value)
# 来自test.py文件夹的测试
# dict = {'translateResult': [[{'tgt': 'hello', 'src': '你好'}]], 'errorCode': 0, 'type': 'zh-CHS2en'}
# a = dict.get('translateResult')
# for b in a:
# pass
# # print(b[0])
# for value in b[0].values():
# print(value)
if __name__ == '__main__':
# youdao = Youdao('力量')
# youdao.run()
word = input('输入您想翻译的单词或句子:')
youdao = Youdao(word)
youdao.run()
|