本帖最后由 mikeee 于 2020-9-22 14:51 编辑
"""
https://www.52pojie.cn/thread-1272004-1-1.html
"""
import requests
import time
import random
import hashlib
from urllib import parse
USERAGENT = "5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4260.0 Safari/537.36 Edg/87.0.637.0"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4260.0 Safari/537.36 Edg/87.0.637.0",
"Referer": "http://fanyi.youdao.com/",
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
}
# 此处的cookies是第一次访问http://fanyi.youdao.com/获得
# 如果访问失败,尝试重新获取cookie
cookies = {
# "OUTFOX_SEARCH_USER_ID": "1816945418@10.169.0.83"
"OUTFOX_SEARCH_USER_ID": "-1545285618@10.169.0.83"
}
sess = requests.session()
sess.get('http://fanyi.youdao.com/')
# cookies = dict(sess.cookies.items())
# cookies = sess.cookies
DATA_KEY = "i={keyword}&from=AUTO&to=AUTO&smartresult=dict&client=fanyideskweb&salt={salt}&sign={sign}<s={lts}&bv={bv}&doctype=json&version=2.1&keyfrom=fanyi.web&action=FY_BY_REALTlME"
SIGN_KEY = "fanyideskweb{keyword}{salt}]BjuETDhU)zqSxf-=B#7m"
def get_md5(value):
md5 = hashlib.md5()
md5.update(value.encode('utf-8'))
md5_digest = md5.hexdigest()
return md5_digest
def get_result(keyword):
# 获取13位时间戳
time_stamp = str(int(time.time()))
lts = time_stamp
salt = lts + str(random.randint(0, 9))
# 获取sign和bv的md5加密值
sign = get_md5(SIGN_KEY.format(keyword=keyword, salt=salt))
bv = get_md5(USERAGENT)
# 发起请求
url = "http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule"
data = DATA_KEY.format(keyword=parse.quote(keyword), salt=salt, sign=sign, lts=lts, bv=bv)
# response = requests.post(url=url, data=data, headers=headers, cookies=cookies)
response = sess.post(url=url, data=data, headers=headers)
if response.status_code == 200:
json_dict = response.json()
try:
return json_dict.get("translateResult")[0][0].get("tgt", None)
except Exception as e:
return json_dict
else:
return None
if __name__ == '__main__':
print(get_result("你今天都做了什么"))
感谢无私分享
改成了用 requests.Session() 自动获取 cookies。好像可行。 |