python爬取百度翻译api实现英文到中文的翻译

# encoding:'utf-8'
import requests
import json


class FanYi():
    def __init__(self, query_string):
        self.url = "https://fanyi.baidu.com/transapi"
        self.query_string = query_string

    def get_post_data(self):
        post_data = {"query": self.query_string,
                     "from": "en",
                     "to": "zh"}
        return post_data

    def parse_url(self, url, data):
        response = requests.post(url, data=data)
        return response.content.decode()

    def get_ret(self, json_str):  # 提取数据
        temp_dict = json.loads(json_str)
        str = temp_dict["data"][0]["dst"]
        print(str)

    def run(self):
        post_data = self.get_post_data()
        json_str = self.parse_url(self.url, post_data)
        self.get_ret(json_str)


if __name__ == '__main__':
    fanyi = FanYi("I am administrator")
    fanyi.run()

 

你可能感兴趣的:(Python)