注册
到百度翻译的官网注册账号获取appid和密钥地址
注意看一下产品服务,有的服务有字符数量限制超过了要收费。
通用翻译api调用(标准版完全免费)
输入的参数有
签名生成的算法
import requests
import hashlib # 用来计算MD5码
def fanyi(shuru):
header = {
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.96 Safari/537.36',
'Content-Type': 'application/x-www-form-urlencoded'
}
appid, salt, key = "appid", "随机码", "密钥"
q = shuru
sign = appid+q+salt+key
md5 = hashlib.md5()
md5.update(sign.encode('utf-8')) # 生成签名计算MD5码
data = {
"q": q,
"from": "auto",
"to": "zh",
"appid": appid,
"salt": salt,
"sign": md5.hexdigest()
}
response = requests.post('https://fanyi-api.baidu.com/api/trans/vip/translate',headers=header, data=data ) # 发送post请求
text = response.json() # 返回的为json格式用json接收数据
print(text)
shuchu = text['trans_result'][0]['dst']
return shuchu
print(fanyi('hello world'))
输出