zoukankan      html  css  js  c++  java
  • python+requests 百度翻译接口自动化测试

    #!/usr/local/bin/python3.7
    
    """
    @File    :   baidu_translate.py
    @Time    :   2020/03/28
    @Author  :   Mozili
    
    """
    
    import requests
    import random
    import hashlib
    import urllib
    import json
    
    class BaiduTranslate(object):
        def __init__(self,word):
            # 需要翻译的元素
            self.q = word
            # 翻译源语言
            self.fromLang = 'en'
            # 译文语言
            self.toLang = 'zh'
            # 通用翻译API HTTP地址
            self.translate_api_url = 'http://api.fanyi.baidu.com/api/trans/vip/translate'
    
            # appid&密钥(自己注册获得)
            self.appid = 'xxx'
            self.secretKey = 'xxx'
    
            # 随机数
            self.salt = random.randint(32768,65536)
            # 签名(appid+q+salt+密钥的md5值)
            self.sign = self.appid + self.q + str(self.salt) + self.secretKey
            # 创建hash对象
            m = hashlib.md5()
            # 更新hash对象
            m.update(self.sign.encode('utf-8'))
            # 将hash中的数据转换成数字,其中只包含十六进制的数字
            self.sign = m.hexdigest()
         # 拼接完整请求 self.my_url
    = self.translate_api_url + '?q=' + urllib.request.quote(self.q) + '&from=' + self.fromLang + '&to=' + self.toLang + '&appid=' + self.appid + '&salt=' + str(self.salt) + '&sign=' + self.sign def en_translate_zh(self): re = requests.request('get',self.my_url) print(' re.text',re.text)
    # 转换成json格式 re_json
    = json.loads(re.text) print(' re_json',re_json) if __name__ == "__main__": bt = BaiduTranslate('test') bt.en_translate_zh()

    说明:

    1、百度翻译appid+密钥需要自己注册获得,获取方法链接:https://mc.viyf.org/get_baidu_appid/

    2、百度翻译技术文档中中可查看sign生成方式、接参数说明等,链接:https://api.fanyi.baidu.com/doc/21

    3、上面代码运行结果:

    4、运行过程中如果出现报错,会有错误吗,具体错误原因请查看百度翻译支持文档:https://api.fanyi.baidu.com/doc/21

  • 相关阅读:
    Linux Ubuntu安装Mysql5.7
    Linux Ubuntu安装maven3.3.9
    Linux Ubuntu安装tomcat9
    Linux Ubuntu安装JDK1.8
    Win10 U盘安装ubuntu16.04 LTS 双系统
    Linux Mysql5.7 常用语句与函数
    在Linux CentOS 6.6上安装Python 2.7.9
    CentOS6下docker的安装和使用
    How to Install Apache Solr 4.5 on CentOS 6.4
    SpringBoot的日志管理
  • 原文地址:https://www.cnblogs.com/lxmtx/p/12587092.html
Copyright © 2011-2022 走看看