#安装:pip3 install requests
#请求
import requests
requests.get(url, params=None, **kwargs) #获取
requests.post(url, data=None, json=None, **kwargs) #新增
requests.put(url, data=None, **kwargs) #更新
requests.delete(url, **kwargs) #删除
requests.head(url, **kwargs) #请求头
requests.patch(url, data=None, **kwargs) #局部更新
requests.options(url, **kwargs)
requests.request(
method='get', #请求方式
url="", #请求地址
params={}, #get形式传的参数 request.get()
data={}, #发送请求体内容
json={}, #发送请求体内容,内部json.dumps({......}) 相当于data=json.dumps({}) 并且Content-Type是 {'Content-Type': 'application/json'}
headers={},
cookies={},
proxies={}, #代理
files=(), #上传文件
auth=None #简单常用的验证规则
timeout=(1,2) #连接超时,响应超时
allow_redirects=True, #允许重定向
stream=True, #流式下载
cert=(), #证书 一般用于自己创建的证书
)
#response属性
import requests
res=requests.get('http://www.jianshu.com')
# respose属性
print(res.text)
print(res.content) #二进制数据
print(res.json()) #直接获取json数据
print(res.status_code)
print(res.headers)
print(res.cookies)
print(res.cookies.get_dict())
print(res.cookies.items())
print(res.url)
print(res.history)
print(res.encoding)
#关闭:response.close()
from contextlib import closing
with closing(requests.get('xxx',stream=True)) as response:
for line in response.iter_content():
pass
#相应时间
import requests
r = requests.get("http://www.cnblogs.com/")
print(r.elapsed)
print(r.elapsed.total_seconds()) #总时长,单位秒
print(r.elapsed.microseconds) #(>= 0 and less than 1 second) 获取微秒部分,大于0小于1秒
print(r.elapsed.seconds) #(>= 0 and less than 1 day) 秒,大于0小于1天
print(r.elapsed.days) #以天为单位
print(r.elapsed.max) #max = datetime.timedelta(999999999, 86399, 999999) 最大时间
print(r.elapsed.min) #min = datetime.timedelta(-999999999) 最小时间
print(r.elapsed.resolution) #resolution = datetime.timedelta(0, 0, 1) 最小时间单位
运行结果:
0:00:00.043166
0.043166
43166
0
0
999999999 days, 23:59:59:999999
-999999999 days, 0:00:00
0:00:00.000001