用爬虫模拟百度翻译

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”
翻译结果: 你好世界

你可能感兴趣的:(python,爬虫)