基本的get请求
response = requests.get(url)
带参数的get请求
data = {}
response = requests.get(url, params=data)
直接解析json数据
response = requests.get(url)
print(response.json())
获取二进制数据
response = requests.get(url)
print(response.content)
添加headers
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36'
}
response = requests.get(url, headers=headers)
基本的post请求
data = {} --请求体
headers = {} --请求头
response = requests.post(url, data=data, headers=headers)
response属性
状态码------response.status_code
响应头------response.headers
cookies------response.cookies
url------response.url
历史记录------response.history
文件上传
files = {'file': open("E:/imgs/01.jpg",'rb')}
response = requests.post(url, files=files)
print(response.text)
维持会话
s = requests.Session() ------创建session对象用来存储会话信息
s.get('www.baidu.com') ------访问百度之后,所有的session信息就被放在session对象中了
response = s.get(url) ------使用session对象访问百度的其他子页面时,就相当于携带session访问了
print(response.text)
证书验证
response = requests.get(url, verify=False) ------默认为True,开启证书验证
response = requests.get(url, cert=['','']) ------使用本地证书
代理设置
proxies = {"http":"ip","https":"ip"}
response = requests.get(url, proxies=proxies)
超时设置
resposne = requests.get(url, timeout = 1)
认证设置
#如果需要用户名和密码才能登陆网站,则需要认证设置auth=()
import requests
response = requests.get(url,auth=('user','password'))
#或者
from requests.auth import HTTPBasicAuth
response = requests.get(url,auth=HTTPBasicAuth('user','password'))
异常处理
from requests.exceptions import HTTPError,...