【Python】百度翻译的爬虫实现(后篇)

 这个程序可以实现中英文的自动识别然后进行翻译

看着程序就很好理解。

import requests

import json

class Translation():
    '''翻译'''
    def __init__(self,content):
        self.content = content
        self.url = "http://fanyi.baidu.com/basetrans"
        self.headers = {"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"}


    def langdetect(self):
        detect_url = "http://fanyi.baidu.com/langdetect"
        detect_data = {"query": self.content}
        response = requests.post(detect_url,data = detect_data,headers = self.headers)
        detect = response.content.decode()
        detect_json = json.loads(detect)['lan']
        if detect_json =='en':
            data = {"query": self.content,"from": "en","to": "zh"}
        else:
            data = {"query":self.content,"from": "zh","to": "en"}
        return data

    def requests_data(self,data):
        url = "http://fanyi.baidu.com/basetrans"
        response = requests.post(url,data=data,headers =self.headers)
        return  response

    def parse_data(self,response):
        html_str = response.content.decode()
        print("翻译结果是:",json.loads(html_str)["trans"][0]["dst"])

    def run(self):
        data = self.langdetect()
        response = self.requests_data(data)
        self.parse_data(response)

if __name__ == '__main__':
    content = input("请输入要翻译的内容:")
    translation =Translation(content)
    translation.run()

参考页面:https://blog.csdn.net/qwe1110/article/details/79435441

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