When translating some words recently, I have to open chrome every time, and then open Baidu translation, which is very annoying
I suddenly got inspiration yesterday, like calling a simulated browser to try the crawler to get the translated information. Later, I found that urlopen didn't work at all, so trying requests didn't work either.
So I used a simulated browser, and found that the efficiency was really low. Later, Baidu took a look and found that Baidu Translate has an API interface.
However, yesterday the phone was out of power, so today after applying for a developer, I used this api to write a code
Not much to say, paste the code, remove the privacy part, and run directly after adding it, the environment is python3.6
import requests import string import time import hashlib import json #init api_url = "http://api.fanyi.baidu.com/api/trans/vip/translate" my_appid = your id cyber = your key lower_case = list(string.ascii_lowercase) def requests_for_dst(word): #init salt and final_sign salt = str(time.time())[:10] final_sign = str(my_appid)+word+salt+cyber final_sign = hashlib.md5(final_sign.encode("utf-8")).hexdigest() #Difference en,zh construct request parameters if list(word)[0] in lower_case: paramas = { 'q':word, 'from':'en', 'to': 'zh', 'appid':'%s'%my_appid, 'salt':'%s'%salt, 'sign':'%s'%final_sign } my_url = api_url+'?appid='+str(my_appid)+'&q='+word+'&from='+'en'+'&to='+'zh'+'&salt='+salt+'&sign='+final_sign else: paramas = { 'q':word, 'from':'zh', 'to': 'en', 'appid':'%s'%my_appid, 'salt':'%s'%salt, 'sign':'%s'%final_sign } my_url = api_url+'?appid='+str(my_appid)+'&q='+word+'&from='+'zh'+'&to='+'en'+'&salt='+salt+'&sign='+final_sign response = requests.get(api_url,params = paramas).content content = str(response,encoding = "utf-8") json_reads = json.loads(content) print(json_reads['trans_result'][0]['dst']) while True: word = input("Enter the content you want to translate: ") requests_for_dst(word)