1、基本信息
请求地址:url
协议状态码:status_code
请求头:headers
响应内容:text
二进制文件:content
json格式响应文件:json()
编码:encoding
cookies:cookies
请求响应时间:elapsed.total_seconds()
json排序:json.dumps(r.json(),indent=True,ensure_ascii=False)
认证证书:verify=True
2、拉勾网post请求
headers = {'Cookie':'123456789',
'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36 Edg/86.0.622.61',
'referer':'https://www.lagou.com/jobs/list_%E6%B5%8B%E8%AF%95%E5%B7%A5%E7%A8%8B%E5%B8%88/p-city_0?&cl=false&fromSearch=true&labelWords=&suginput=',
'content-type':'application/x-www-form-urlencoded; charset=UTF-8'
}
params = {'needAddtionalResult':False}
data={'first':False,'pn':2,'kd':'测试工程师'}
r = requests.post(url='https://www.lagou.com/jobs/positionAjax.json',
headers=headers,
params=params,
data=data)
print(r.text)
3、data与json的区别
content-type’:’application/x-www-form-urlencoded; charset=UTF-8 and application/json——>发送的是json格式的字符串
data传输的是form表单数据,json传输的是json数据格式
json要满足两个条件:
1、application/json
2、请求参数必须是字典
4、超时处理
在请求中加上timeout
r = requests.post(url='http://127.0.0.1:5000/v1/api/books',json=json,timeout=60)
5、复杂参数处理
datas={'name':'super','age':18,'data':[{'address':'wuhan'},{'address':'hubei'}]}
#先把列表反序列化成字符串
datas['data']=json.dumps(datas['data'])
6、token与Sessioon处理
1、登录获取token
def login(self):
data = {'username':'wuya','password':'asd888'}
r = requests.post(url='http://127.0.0.1:5000/auth',json=data)
return r.json()['access_token']
2、放入headers头中
headers={'Authorization':'jwt {0}'.format(self.login())}
#登录获取cookies
def login(self):
data={'id':'admin','password':'AdJUrorlWKjshy+8ygM5KQ==','authtimeStamp':'1607350740336'}
headers={''}
r=requests.post(url='http://iotwedora.com/monitor/login',
data=data,
headers=headers)
return r.cookies
#获取标题信息
def title(self):
headers = {''}
r = requests.get(url ='http://iotwedora.com/monitor/device/manager/list-fields',
headers=headers,
cookies=self.login()) #重点
print(json.dumps(r.json(),indent=True,ensure_ascii=False))
7、sessions会话对象
import json
import requests
class Test():
#登录获取cookies
def login(self):
s = requests.Session() #重点
data={'id':'admin','password':'AdJUrorlWKjshy+8ygM5KQ==','authtimeStamp':'1607350740336'}
headers={''}
r=s.post(url='http://iotwedora.com/monitor/login',
data=data,
headers=headers)
return s
#获取标题信息
def title(self):
headers = {''}
r = self.login().get(url ='http://iotwedora.com/monitor/device/manager/list-fields',
headers=headers)
print(json.dumps(r.json(),indent=True,ensure_ascii=False))
if __name__ == '__main__':
r = Test()
r.title()
8、鉴权认证
from requesta.auth import HTTPBasicAuth
auth=('账户','密码')
9、文件上传
files={'file':(文件名称,open(文件路径,'rb'),文件类型,{})}
files={'file':('log.jpg',open('c:/log.jpg','rb'),'image/jpeg',{})}