python + requests Baidu translation interface test

# /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):
         # to be translated elements 
        self.q = Word
         # translate From 
        self.fromLang = ' EN ' 
        # target language 
        self.toLang = ' zh '
        # Universal translator API HTTP address 
        self.translate_api_url = ' http://api.fanyi.baidu.com/api/trans/vip/translate ' 

        # AppID & Key (to get themselves registered) 
        self.appid = ' xxx ' 
        self.secretKey = ' XXX ' 

        # nonce 
        self.salt the random.randint = (32768,65536 )
         # signature (appid + q + salt + md5 value of the key) 
        self.sign = self.appid self.q + + STR (self.salt ) + self.secretKey
         # Create an object hash 
        m = hashlib.md5 ()
         # updated hash objects 
        m.update (self.sign.encode (' UTF-. 8 ' ))
         # converted into digital data in the hash, which contains only hexadecimal digits 
        self.sign = m.hexdigest () 
     # splicing complete request 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('\n\t re.text',re.text)
# 转换成json格式 re_json
= json.loads(re.text) print('\n\t re_json',re_json) if __name__ == "__main__": bt = BaiduTranslate('test') bt.en_translate_zh()

Description:

1, Baidu translation appid + keys need to get themselves registered, method for obtaining link: https: //mc.viyf.org/get_baidu_appid/

2, Baidu translation technology documentation can view the sign generation mode, then the parameter descriptions, link: https: //api.fanyi.baidu.com/doc/21

3, the above code is run results:

 

4, during operation if there is an error, it will be wrong, the specific cause of the error, please see Baidu translation support document: https: //api.fanyi.baidu.com/doc/21

 

Guess you like

Origin www.cnblogs.com/lxmtx/p/12587092.html