最新百度翻譯爬蟲 手機版(python爬蟲)
阿新 • • 發佈:2018-12-21
環境:python3
直接上程式碼:
#coding=utf-8 import requests import json class BaiDuTranslatePhone: def __init__(self): self.query=input("請輸入要翻譯的內容:") self.url = "https://fanyi.baidu.com/basetrans" self.data={ "query": self.query, "from": "zh", "to": "en" } self.headers={ "Host": "fanyi.baidu.com", "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1", "Referer": "https://fanyi.baidu.com/?aldtype=16047" } def run(self): post_response = requests.post(url=self.url, data=self.data, headers=self.headers) self.strs = post_response.content.decode() #print(self.strs) #print("self.strs type:"+str(type(self.strs))) def get_result(self): result_dict = json.loads(self.strs) #print("result_dict type:"+str(type(result_dict))) result=result_dict['trans'][0]['dst'] if len(result_dict['trans']) > 0 else None print("翻譯結果為:") print(result) if __name__ == '__main__': while True: translate=BaiDuTranslatePhone() translate.run() translate.get_result()