Python对于requests库的使用
一、requests的基本方法使用
requests库是一个非常流行的HTTP库,用于发送HTTP请求。
安装requests模块(一般安装python都自带,无需安装)
pip install requests
1.get()方法
发送 GET 请求,一般用于从服务器获取数据。
get()方法返回的对象信息:
- .text:获取响应内容(字符串格式)
- .status_code:获取 HTTP 响应状态码(如 200、404)
- .herders:获取响应头信息
- .url:获取最终的请求 URL
- .cookies:获取 Cookies
- .content:以 bytes 类型返回响应内容
- .elapsed:获取请求耗时
- .request:获取原始请求对象
- .json():解析 JSON 数据并返回 Python 字典
- .encoding:获取或设置响应的编码格式
- .raise_for_status():检查 HTTP 请求是否成功,否则抛出异常
- .iter_content():以流的方式读取内容(适用于大文件)
- .iter_lines():逐行读取响应内容
使用方法:
requests.get(url, params, herders, auth, timeout, cert, ...)
"""
url 访问地址(必填)
params 查询参数,以字典格式传递
headers 请求头,可选
auth 用户名和密码
timeout 设置请求超时
cert 指定证书
"""
使用实例(以请求es为例):
import requests
url = 'http://localhost:9200/_cat/indices?h=index,health,docs.count,store.size&format=json'
response = requests.get(url)
print('响应内容:', response.text)
print('状态码:', response.status_code)
2.post()方法
发送 POST 请求,一般用于提交表单或上传数据。
使用方法:
requests.post(url, params, headers, timeout)
"""
url 访问地址(必填)
params 查询参数,以字典格式传递
headers 请求头,可选
auth 用户名和密码
timeout 设置请求超时
"""
使用实例:
import requests
url = "http://localhost:9200/my_index/_delete_by_query"
# 发送查询参数
params = {
"query": {
"match_all": {}
}
}
# 请求头设置
headers = {"User-Agent": "Mozilla/5.0"}
response = requests.get(url, params=params, headers=headers, timeout=5)
print(response.json())
3.put()方法
使用方法:
requests.put(url, params, headers, timeout)
"""
url 访问地址(必填)
params 查询参数,以字典格式传递
headers 请求头,可选
auth 用户名和密码
timeout 设置请求超时
"""
使用实例:
import requests
url = "http://localhost:9200/my_index"
headers = {"Content-Type": "application/json"}
data = {
"settings": {
"number_of_shards": 1,
"number_of_replicas": 1
},
"mappings": {
"properties": {
"field1": { "type": "text" },
"field2": { "type": "keyword" },
"field3": { "type": "date" }
}
}
}
response = requests.put(url, headers=headers, data=json.dumps(data), timeout=5)
print(response.json())
4.delete()方法
使用方法:
requests.delete(url, params, headers, timeout)
"""
url 访问地址(必填)
params 查询参数,以字典格式传递
headers 请求头,可选
auth 用户名和密码
timeout 设置请求超时
"""
使用实例:
import requests
url = "http://localhost:9200/my_index"
response = requests.delete(url)
二、requests.request()方法
requests.request()方法更加通用,可以用于发送任意类型的HTTP请求。
基本使用方法
使用方法:
requests.delete(url, params, headers, timeout)
"""
method 请求方法(必填)
url 访问地址(必填)
params 查询参数,以字典格式传递
headers 请求头,可选
auth 用户名和密码
timeout 设置请求超时
"""
使用实例:
import requests
url = "http://localhost"
# get方法
rs_get = requests.request('get', url)
# post方法
rs_post = requests.request('post', url)
# put方法
rs_put = requests.request('put', url)
# delete方法
rs_delete = requests.request('delete', url)
print(rs_get.status_code, rs_get.text)
高级用法
如果需要添加请求头,以及需要用户名和密码
import requests
url = "http://localhost"
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0"}
rs = requests.request('get', url, headers=headers, auth=('username', 'password'))
print(rs.status_code, rs.text)
三、requests的其他方法
head()方法
HEAD 请求类似 GET,但只返回响应头,不返回正文。
import requests
response = requests.head('http://localhost')
print(response.headers)
options()方法
OPTIONS 请求用于获取服务器允许的 HTTP 方法。
import requests
url = 'http://lcoalhost'
response = requests.options(url)
# 服务器支持的 HTTP 方法
print(response.headers.get("Allow"))
处理请求超时
跟其他程序一样用try语句来实现
import requests
try:
response = requests.get('http://localhost', timeout=5)
print(response.json())
except requests.exceptions.Timeout:
print("请求超时")
处理异常
import requests
try:
response = requests.get('http://localhost', timeout=5)
# 检查是否返回 HTTP 200 之外的状态码
response.raise_for_status()
print(response.json())
except requests.exceptions.RequestException as e:
print(f"请求错误: {e}")