代码拉取完成,页面将自动刷新
# -*- coding: utf-8 -*-
import hashlib
import requests
import time
import random
import re
import json
import user_agent
class translate_youdao():
def __init__(self, msg):
self.msg = msg
self.url = "http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule"
self.get_ts = self.get_ts()
self.user_agent = user_agent.RandomUserAgent
def get_ts(self):
# 获取当前时间戳
s = int(time.time() * 1000)
return str(s)
def get_salt(self):
# salt参数 由时间戳 + 一位随机数组成
s = str(int(time.time() * 1000)) + str(random.randint(0, 9))
return s
def get_sign(self):
e = self.msg
i = self.get_salt()
words = "fanyideskweb" + e + i + "mmbP%A-r6U3Nw(n]BjuEU"
# MD5加密
m = hashlib.md5()
m.update(words.encode("utf-8"))
return m.hexdigest()
def get_bv(self):
n = hashlib.md5()
n.update(self.user_agent.encode("utf-8"))
return n.hexdigest()
def fanyi(self):
form_data = {
"i": self.msg,
"from": "zh-CHS", #原AUTO zh-CHS
"to": "JP", #原JP ja 日语
"smartresult": "dict",
"client": "fanyideskweb",
"salt": self.get_salt(),
"sign": self.get_sign(),
"ts": self.get_ts,
"bv": self.get_bv(),
"doctype": "json",
"version": "2.1",
"keyfrom": "fanyi.web",
"action": "FY_BY_REALTlME"
}
headers = {
"Referer": "http://fanyi.youdao.com/",
"User-Agent": self.user_agent
}
res = requests.get("http://fanyi.youdao.com/", headers=headers)
cookies = res.cookies
dict = requests.utils.dict_from_cookiejar(cookies)
if "OUTFOX_SEARCH_USER_ID" in dict:
headers = {
# "OUTFOX_SEARCH_USER_ID": dict["OUTFOX_SEARCH_USER_ID"],
"OUTFOX_SEARCH_USER_ID": dict["OUTFOX_SEARCH_USER_ID"],
"Referer": "http://fanyi.youdao.com/",
"User-Agent": self.user_agent
}
res = requests.post(self.url, headers=headers, data=form_data)
return res.content.decode().strip()
else:
return "返回出错"
def youdao(words):
'''
自动翻译,将中文翻译成英文
:param words:要翻译的中文
:return: 返回英文结果
'''
translate_tgt = []
youdao = translate_youdao(words)
result = youdao.fanyi()
result_dict = json.loads(result)
translateResult = result_dict.get('translateResult',{})
for tgt_list in translateResult:
for tgt in tgt_list:
# print('-' * 50)
res_tgt = tgt.get('tgt', {})
translate_tgt.append(res_tgt)
# return translate_tgt
p_text = []
for p in translate_tgt:
# print(p)
if p == '':
p_text.append('\r\n')
else:
p_text.append(p)
return ''.join(p_text)
if __name__ == '__main__':
with open('china.txt','r',encoding='utf-8') as f:
text = f.read()
res = youdao(text)
print(res)
# p_text = []
# for p in res:
# # print(p)
# if p =='':
# p_text.append('\r\n')
# else:
# p_text.append(p)
#
# print(''.join(p_text))
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。