难点:签名获取
细节:编码问题 utf-8
# coding=utf-8
import requests
import json
import execjs # 需要pip install PyExecJS
import sys
class Baidufanyi:
def __init__(self, trans_str):
self.trans_str = trans_str
self.lang_detect_url = "https://fanyi.baidu.com/langdetect"
self.trans_url = "https://fanyi.baidu.com/basetrans"
self.headers = {"user-agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1"}
self.sign = self.get_baidu_sign()
def parse_url(self, url, data): # 发送post 请求,获取响应
response = requests.post(url, data=data, headers=self.headers)
# print(response.content.decode())
return json.loads(response.content.decode())
def get_baidu_sign(self): # 获取js生成的签名参数
with open("BaidSign.js", encoding='utf-8') as f:
sign = execjs.compile(f.read()).call("a", self.trans_str)
return sign
def get_ret(self, dict_response):
ret = dict_response["trans"][0]['dst']
print("结果:%s" % ret)
def run(self): # 实现主要逻辑
# 1.获取语言类型
# 1.1 准备post的url地址,post_data
lang_detect_data = {"query": self.trans_str}
# 1.2 发送post请求,获取相应
lang = self.parse_url(self.lang_detect_url, lang_detect_data)["lan"]
# 1.3 提取语言类型
# 2.准备post的数据
trans_data = {"query": self.trans_str, "from": "zh", "to": "en", "token": "1e6a95674719860752458b73e733e438", "sign": self.sign} if lang == "zh" else \
{"query": self.trans_str, "from": "en", "to": "zh", "token": "1e6a95674719860752458b73e733e438", "sign": self.sign}
# 3.发送请求,获取响应
dict_response = self.parse_url(self.trans_url, trans_data)
# 4.提取翻译的结果
self.get_ret(dict_response)
if __name__ == '__main__':
trans_str = sys.argv[1] # "你好"
baidu_fanyi = Baidufanyi(trans_str)
baidu_fanyi.run()
下载地址 :https://download.csdn.net/download/baidu_21088845/12118257