百度翻译地址:/
上篇文章我使用了爬虫获取了有道翻译的接口,这次通过正规渠道获取翻译结果
百度翻译开放平台:http://api./api/trans/product/index
1、按照提示注册账号,获取 APP ID 和 密钥
2、申请开通通用翻译API服务
3、参考百度翻译提供的通用翻译API技术文档 接入方式
4、可以参考百度翻译提供的demo,有各种语言的调用实现,不过我没有运行成功(我的环境是py3)
5、找到百度翻译提供的返回示例,获取结果:
{"from":"en","to":"zh","trans_result":[{"src":"apple","dst":"苹果"}]}
完整代码
# coding=utf8import requests import hashlibimport randomappid = 'xxx' # 你的appidsecretKey = 'xxx' # 你的密钥def baidu_fanyi(query):salt = random.randint(1, 10) # 随机数code = appid + query + str(salt) + secretKeysign = hashlib.md5(code.encode()).hexdigest() # 签名api = "http://api./api/trans/vip/translate"data = {"q": query,"from": "auto","to": "auto","appid": appid,"salt": salt,"sign": sign}response = requests.post(api, data)try:result = response.json()dst = result.get("trans_result")[0].get("dst")except Exception as e:dst = queryfinally:return dstif __name__ == '__main__':query ="Apple"ret = baidu_fanyi(query)print(ret)# 苹果
说明:将代码中的以下参数替换为申请的值即可调用,环境是python3,如果是python2需要对md5函数那几行单独处理
appid = 'xxx' # 你的appidsecretKey = 'xxx' # 你的密钥
参考:
百度翻译通用翻译API技术文档 #接入方式