requests库的post请求
requests库的post请求
#coding:utf-8 import requests import json class Trans(object): def __init__(self, word): self.url = 'http://fanyi.baidu.com/v2transapi' self.headers = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.89 Safari/537.36' } self.post_data = { 'from': 'zh', 'to': 'en', 'query': word, 'transtype': 'translang', 'simple_means_flag': 3 } def get_data(self): response = requests.post(self.url, headers=self.headers, data=self.post_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] # 构建请求头 # 构建post数据 # 发送请求获取响应 data = self.get_data() # 解析响应 self.parse_data(data) if __name__ == '__main__': trans = Trans('深圳') trans.run()