1、request方法 发送get请求
from urllib import request import json url='xxx/stu_info?stu_name=xiaohei' req=request.urlopen(url,)#打开一个url发送get请求 content=req.read().decode()#获取返回结果 res_dic=json.loads(content)#返回结果转成字典 if res_dic.get('error_code')==0: print('测试通过') else: print('测试失败',res_dic)
2、request方法 发送post请求
from urllib import request,parse url='http:xxx/login' data={ 'username':'admin', 'passwd':'aA123456' }#请求数据 data=parse.urlencode(data) #urlencode自动拼好参数 req=request.urlopen(url,data.encode()) #发post请求 print(req.read().decode())
3、requests方法 发送get请求
import requests url='http://xxx/stu_info' data={'stu_name':'小黑'} #请求数据 req=requests.get(url,params=data) #发get请求 print(req.json()) #字典 print(req.text)#string,json串
4、requests方法 发送post请求
import requests url='http://xxx/api/user/login' data={'username':'niuhanyang','passwd':'aA123456'} #请求数据 req=requests.post(url,data)#发送post请求 print(req.json())
5、入参是json类型
import requests,random url='http://xxx/api/user/add_stu' phone=random.randint(10000000000,99999999999) data={ "name":"刘佳", "grade":"天蝎座", "phone":phone, "sex":"女", "age":28, "addr":"河南省济源市北海大道32号" } req=requests.post(url,json=data) print(req.json())
6、检验cookie
import requests url='http://xxx/api/user/gold_add' data={'stu_id':'468','gold':999999} cookie={'niuhanyang':'337ca4cc825302b3a8791ac7f9dc4bc6'} req=requests.post(url,data,cookies=cookie) print(req.json())
7、添加header
import requests url='http://xxx/api/user/all_stu' header={'Referer':'http://api.nnzhp.cn/'} req=requests.get(url,headers=header) print(req.json())
8、上传文件
import requests url='http://xxx/api/file/file_upload' #data={'file':open('笔记',encoding='utf-8')} #有中文要加utf-8 data={'file':open(r'C:\Users\acer\Desktop\QQ图片20180331170810.png','rb')} #打开图片,以二进制的方式打开才行 req=requests.post(url,files=data) print(req.json())
9、下载文件或图片等
url='http://xxx/wp-content/uploads/2018/01/soup.jpg' req=requests.get(url) fw=open('a.jpg','wb') fw.write(req.content) #保存到本地
url='http://xxx/archives/630' req=requests.get(url) fw=open('pyquery.html','wb') fw.write(req.content) #保存到本地