1. Request method sends get requests
fromUrllibImportRequestImportJsonurl='Xxx/stu_info?stu_name=xiaohei'req=request.urlopen (URL,)#open a URL to send a GET requestContent=req.read (). Decode ()#Get return resultsRes_dic=json.loads (content)#return results to dictionaryifRes_dic.get ('Error_code')==0:Print('Test Pass')Else: Print('Test Failed', Res_dic)
2. Request method to send post requests
fromUrllibImportRequest,parseurl='Http:xxx/login'Data={ 'username':'Admin', 'passwd':'aA123456' }#Request DataData=parse.urlencode (data)#UrlEncode automatically spell the parameters.Req=request.urlopen (Url,data.encode ())#send a POST requestPrint(Req.read (). Decode ())
3. Requests method Send GET request
Import requestsurl='http://xxx/stu_info'data={'stu_name ':' small black '} # request Data # send GET request Print(Req.json ()) # dictionary print(req.text)# String,json string
4. Requests method Send POST request
import Requestsurl =" http://xxx/api/user/login " data ={ " Username ": " Niuhanyang ", " passwd ": " aA123456 "} # Request Data Req=requests.post (url,data) # Send POST request print (Req.json ())
5. The entry parameter is JSON type
ImportRequests,randomurl='Http://xxx/api/user/add_stu'Phone=random.randint (10000000000,99999999999) Data={ "name":"Liu Jia", "Grade":"Scorpio", "Phone":p Hone,"Sex":"female", " Age": 28, "Addr":"No. 32nd Beihai Road, Jiyuan, Henan province"}req=requests.post (url,json=data)Print(Req.json ())
6. Inspection cookie
ImportRequestsurl='Http://xxx/api/user/gold_add'Data={'stu_id':'468','Gold': 999999}cookie={'Niuhanyang':'337ca4cc825302b3a8791ac7f9dc4bc6'}req=requests.post (url,data,cookies=cookies)Print(Req.json ())
7. Add Header
Import requestsurl='http://xxx/api/user/all_stu'header={' Referer':'http://api.nnzhp.cn/'}req=requests.get (URL, headers=header)print(Req.json ())
8. Uploading Files
import Requestsurl =" http://xxx/api/file/file_upload " # data={' file ': Open (' Notes ', encoding= ' Utf-8 ')} #有中文要加utf-8 data={" file ": Open (r< Span style= "COLOR: #800000" > " c:\users\acer\desktop\qq picture 20180331170810.png ", " RB ")} # Open the picture and open it in a binary way req=requests.post (url,files=data) print (Req.json ())
9, download files or pictures, etc.
Url='http://xxx/wp-content/uploads/2018/01/soup.jpg'req=Requests.get ( URL) FW=open ('a.jpg','wb') fw.write ( req.content) # save to local
Url='http://xxx/archives/630'req=requests.get (URL) FW=open (' pyquery.html','wb') fw.write (req.content) # Save to local
Python Learning (26) network programming