导入requests包
import requests
http请求构造
发送一个get请求
res = requests.get(“http://httpbin.org”)
发送一个post请求
res = requests.post(‘http://httpbin.org/post’,json={‘k’:‘v’})
发送一个put请求
res = requests.put(‘http://httpbin.org/put’,json={‘k’:‘v’})
发送一个delete请求
res = requests.delete(‘http://httpbin.org/delete’,json={‘k’:‘v’})
发送一个options 请求
res = requests.options(‘http://httpbin.org/get’)
发送一个head 请求
res = requests.head(‘http://httpbin.org/get’)
获取回应的状态码
print(res.status_code)
获取回应的包头
print(res.headers)
获取回应的内容体
print(res.text)
也可以直接使用 request 函数,传入不同的方法
发送get请求
res = requests.request(‘get’,“http://httpbin.org”)
发送post请求
res =requests.request(‘post’,“http://httpbin.org/post”,json={‘k’:‘v’})
发送put请求
res =requests.request(‘put’,“http://httpbin.org/put”,json={‘k’:‘v’})
发送delete请求
res =requests.request(‘delete’,“http://httpbin.org/delete”,json={‘k’:‘v’})
--------------------------------------------------
verify参数(默认为ture)False为忽略对 SSL 证书的验证
res =requests.request(‘delete’,“http://httpbin.org/delete”,verify=False)
proxies参数,设置代理,可以分别设置 HTTP 请求和 HTTPS 请求的代理。
px = {
‘http’: ‘http://10.10.1.10:3128’,
‘https’: ‘http://10.10.1.10:1080’,
}
requests.get(‘https://api.github.com/events’, proxies=px)
allow_redirects 参数,控制是否启用重定向,True 为启用,False 为禁用
res = requests.get(‘http://github.com’, allow_redirects=False)
print(r.status_code)
timeout参数,设定超时时间
res = requests.get(‘http://github.com’, timeout=0.001)
注意:timeout 仅对连接过程有效,与响应体的下载无关。timeout 并不是整个下载响应的时间限制,而是如果服务器在 timeout 秒内没有应答,将会引发一个异常(更精确地说,是在 timeout 秒内没有从基础套接字上接收到任何字节的数据时),如果不设置 timeout,将一直等待。
files 参数,上传文件,dict 格式
files = {‘file’: open(‘report.xls’, ‘rb’)}
res = requests.post(‘http://httpbin.org/post’, files=files)
header 参数,通过传入 dict 定制请求头
headers = {‘user-agent’: ‘my-app/0.0.1’}
res = requests.get(‘https://api.github.com/some/endpoint’, headers=headers)
data 参数,发送编码为表单形式的数据单
ddd = {‘key1’: ‘value1’, ‘key2’: ‘value2’}
res = requests.post(“http://httpbin.org/post”, data=ddd)