这章我就来将有道的获取翻译内容部分进行补充,希望过审啊,正题开始,依旧是打开翻译网页然后f12调出开发者模式,然后输入一个你想要翻译的文字,然后获取到他的post请求链接
分析
这个请求地址我们将其复制下来,用python的requests库对其进行请求,然后将request headers的部分数据或全部数据做成一个字典作为请求头。以及我们上一篇所获取到的参数也做出一个字典使用。然后进行请求对获得的json进行优化处理获取我们所需的翻译内容即可。
实现
导库
import requests
import TestYoudao
我这里对获取参数的方法写在了另一个文件下所有这里对他进行导入,才能使用他里面的方法。
TestYoudao
def demoTestYoudao(need):
quary = need
with open('youdaoTran.js', 'r', encoding='utf-8') as f:
res = execjs.compile(f.read())
sj = res.call('tr', quary)
return sj
# print (sj)
def to_lang(lang):
return lang
mian代码
def demoTranYoudao(need,lang):
quary = need
resp = TestYoudao.demoTestYoudao(need)
url = "https://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule"
headers = {
"Accept": "application/json, text/javascript, */*; q=0.01",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "zh-CN,zh;q=0.9",
"Connection": "keep-alive",
"Content-Length": "238",
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
"Cookie": "OUTFOX_SEARCH_USER_ID=102813728@10.110.96.158; JSESSIONID=aaaL85FSqu_UAesO5_D7x; OUTFOX_SEARCH_USER_ID_NCOO=1222843384.2482185; ___rl__test__cookies=1644401893098",
"Host": "fanyi.youdao.com",
"Origin": "https://fanyi.youdao.com",
"Referer": "https://fanyi.youdao.com/",
"sec-ch-ua": '" Not A;Brand";v="99", "Chromium";v="98", "Google Chrome";v="98"',
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": "Windows",
"Sec-Fetch-Dest": "empty",
"Sec-Fetch-Mode": "cors",
"Sec-Fetch-Site": "same-origin",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.81 Safari/537.36",
"X-Requested-With": "XMLHttpRequest"
}
dic = {
"i": quary,
"from": "AUTO",
"to": TestYoudao.to_lang(lang),
"smartresult": "dict",
"client": "fanyideskweb",
"salt": resp["salt"],
"sign": resp["sign"],
"lts": resp["lts"],
"bv": resp["bv"],
"doctype": "json",
"version": "2.1",
"keyfrom": "fanyi.web",
"action": "FY_BY_REALTlME"
}
resp = requests.post(url=url, headers=headers, data=dic)
translate = resp.json()["translateResult"][0][0]["tgt"]
# translate = resp.json()
print(f"翻译结果为:{translate}")
if __name__ == '__main__':
while True:
lang = input("你想要翻译为什么语言中文(zh-CHS),英文(en),韩语(ko),日语(ja):")
msg = input("你需要翻译的内容:")
if msg == "q":
break
else:
demoTranYoudao(msg, lang)
结果展示
可以看到有道的一个缺点就是只允许中文翻译为其他语言和其他语言翻译为中文,而不支持其他语言互翻。下章预告,google翻译!