用爬蟲模擬百度翻譯
阿新 • • 發佈:2018-12-13
import requests import json import sys class BaiFanyi(): def __init__(self,trant_str): self.trant_str = trant_str self.lan_url = "https://fanyi.baidu.com/langdetect" self.trant_url = "https://fanyi.baidu.com/basetrans" self.headers = {"User-Agent": "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3528.4 Mobile Safari/537.36"} def __parse_url(self,url,data): reponse = requests.post(url,data=data,headers =self.headers) return json.loads(reponse.content.decode()) def __trant_url(self,url,data): reponse_trant_url = requests.post(url,data=data,headers=self.headers) return json.loads(reponse_trant_url.content.decode()) def __show_reslut(self,result): show = result['trans'][0]['dst'] print("翻譯結果:",show) def run(self): # 1、獲取翻譯型別 # 1.1準備post的url地址,post_data post_data = {"query":self.trant_str} # 1.2傳送post請求,獲取相應 lan_result = self.__parse_url(self.lan_url,post_data) # 1.3提取語言型別 lan = lan_result['lan'] #2、準備post資料 trant_data = {"query": self.trant_str, "from": "zh", "to": "en"} if lan == "zh" else {"query": self.trant_str, "from": "en", "to": "zh"} # 3傳送請求、獲取相應 trant_result = self.__trant_url(self.trant_url,trant_data) # 4、提取翻譯的結果 self.__show_reslut(trant_result) if __name__ == "__main__": trant_str = sys.argv[1] baidu_fanyi = BaiFanyi(trant_str) baidu_fanyi.run()
實現效果
PS C:\Users\32165\Desktop\pythonteach> & python c:/pythonteach//c1-百度翻譯.py “你好” 翻譯結果: Hello PS C:\Users\32165\Desktop\pythonteach> & python c:/pythonteach/c1-百度翻譯.py “hello world” 翻譯結果: 你好世界