import json import requests class Trans(object): def __init__(self, juzi): self.juzi = juzi self.base_url = 'http://fanyi.baidu.com/v2transapi' self.headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.89 Safari/537.36' } self.data = { 'query': self.juzi, 'from': 'zh', 'to': 'en', 'transtype': 'translang', 'simple_means_flag': 3 } pass def get_data(self): response = requests.post(self.base_url, headers=self.headers, data=self.data) return response.content.decode() def parse_data(self, data): # 将json字符串换成python字典 dict_data = json.loads(data) # 使用键提取翻译结果 result = dict_data['trans_result']['data'][0]['dst'] print(result) def run(self): # 构建url # 构建headers # 构建post参数 # 发送post请求,获取响应 data = self.get_data() # 解析响应 self.parse_data(data) pass if __name__ == '__main__': trans = Trans('人生苦短,及时行乐') trans.run()
解析json数据,借助在线json工具
www.json.cn