This article ends the use of requests to send network requests. Requests is a useful Python HTTP client library that is often used when writing crawlers and testing server response data. It can be said that requests fully meet the needs of today's network.
The installation method generally uses the $ pip install requests.
To import the requests module at the outset:
Import requests
Send a GET request
url = ' Http://api.xxx.com/api/user/stu_info?stu_name= small black Horse '
req = requests.get (URL) #发送get请求
Print (Req.text) #获取结果
Print (Req.json ()) #获取结果直接就是字典, you must return a JSON string in order to use the. Json method.
Send a POST request
url = ' Http://api.xxx.com/api/user/login '
data = {' username ': ' Xiaohei ', ' passwd ': ' aA123456 '}
req = Requests.post (url,data) #发送post请求, the first parameter is a URL, the second parameter is the requested data
Print (Req.json ())
The import parameter is JSON.
url = ' Http://api.xxx.com/api/user/add_stu '
data = {' name ': ' Ding ', ' Grade ': ' Cancer ', ' phone ': 31971891223}
req = Requests.post (url,json=data) #发送post请求, the first parameter is a URL, the second parameter is the requested data
Print (Req.json ())
Add a cookie
url = ' Http://api.xxx.com/api/user/gold_add '
data = {' stu_id ': 231, ' Gold ': 1000}
Cookie = {' Xiaohei ': ' 6D195100B95A43046D2E385835C6E2C2 '}
req = Requests.post (Url,data,cookies=cookie)
Print (Req.json ())
Add header
Url= ' Http://api.xxx.com/api/user/all_stu '
MPP = {' Referer ': ' http://api.xxx.com/', ' user-agent ': ' Chore '}
res = Requests.get (URL,HEADERS=MPP)
Print (Res.json ())
Uploading files
url = ' Http://api.xxx.com/api/file/file_upload '
f = open (R ' C:\Users\bjxiaohei\Desktop\ad.cpm.schedulingInfo.v1.json ', ' RB ')
R = requests.post (url,files={' file ': F})
Print (R.json ())
Download file
Url= ' http://www.besttest.cn/data/upload/201710/f_36b1c59ecf3b8ff5b0acaf2ea42bafe0.jpg '
r = Requests.get (URL)
Print (R.status_code) #获取请求的状态码
Print (r.content) #获取返回结果二进制格式的
FW = open (R ' bt.jpg ', ' WB ')
Fw.write (r.content)
Fw.close ()
Save Web Page
url = ' http://www.xxx.com/archives/630 '
r = Requests.get (URL)
f = open (' xxx.html ', ' WB ')
F.write (r.content)
F.close ()
Python Learning Notes (12)-Network programming