python-對requests請求簡單的封裝

Tynam.Yang發表於2019-04-12
 1 # coding:utf-8
 2 
 3 import requests
 4 
 5 
 6 class send_request:
 7 
 8     def __init__(self,url,method,data=None):
 9         self.response = self.run_main(url,method,data)
10 
11     def send_get(self, url, data=None):
12         headers = {'content-type': 'charset=utf8'}
13         response = requests.get(url=url, data=data, headers=headers)
14         return response.content.decode('utf-8')
15 
16     def send_post(self, url, data):
17         headers = {'content-type': 'charset=utf8'}
18         response = requests.post(url=url, data=data,headers=headers)
19         return response.content.decode('utf-8')
20 
21     def run_main(self, url, method, data=None):
22         response = None
23         if method == 'get':
24             response = self.send_get(url, data)
25         elif method == 'post':
26             response = self.send_post(url, data)
27         else:
28             response = 'the method is error'
29         return response
30 
31 
32 if __name__ == '__main__':
33     url = 'https://www.baidu.com'
34     data = {
35 
36     }
37     response = send_request(url=url, method='get')
38     print(response.response)

 

相關文章