一文入门:使用 Python的requests 库

简介

requests 是 Python 中一个简单易用的 HTTP 库,用于发送各种 HTTP 请求。它建立在 Python 标准库 urllib 之上,提供了更人性化的接口。

安装 requests

在开始之前,确保你已经安装了 requests 库。如果还没有安装,可以通过 pip 安装:

bash 复制代码
pip install requests

发送一个 GET 请求

让我们从发送一个简单的 GET 请求开始:

python 复制代码
import requests

# 发送 GET 请求
res = requests.get('https://httpbin.org/get')

# 打印响应内容
print(res.text)

处理响应

requests 库返回的响应对象包含了服务器响应的所有信息:

  • response.status_code:状态码。
  • response.text:响应的文本内容。
  • response.json():解析 JSON 响应体。

发送 POST 请求

除了 GET 请求,requests 也支持 POST 请求:

python 复制代码
data = {'key1': 'value1', 'key2': 'value2'}
response = requests.post('https://httpbin.org/post', data=data)

# 检查请求是否成功
if response.ok:
    print('Success!')
else:
    print('Error:', response.status_code)

传递 Headers

有时,你需要自定义请求的 headers,比如模拟浏览器访问:

python 复制代码
headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36'
}
response = requests.get('https://httpbin.org/get', headers=headers)

传递查询参数

使用 params 来传递 URL 的查询参数:

python 复制代码
# 传递查询参数
params = {
    'pn': 10,
    'size': 20
}
# headers = {
#     'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36'
# }
res = requests.get('https://httpbin.org/get', params=params)
for k, v in res.json().items():
    print(k, v)

文件上传

requests 支持文件上传:

python 复制代码
file_path = './2.jpg'

# 打开文件('rb' 表示以二进制模式读取)
with open(file_path, 'rb') as file:
    # 准备文件数据
    files = {'file': (file_path, file)}

    # 发送 POST 请求
    # 'https://httpbin.org/get' 是服务器接收文件的端点
    response = requests.post('https://upfile.live/assets/images/loading.gif', files=files)

    # 检查请求是否成功
    if response.ok:
        print('File uploaded successfully.')
    else:
        print('Failed to upload file.')

会话管理

使用 Session 对象可以维持某些参数和 Cookies:

python 复制代码
with requests.Session() as session:
    session.headers.update({'Authorization': 'Bearer your_token'})
    response = session.get('https://httpbin.org/get')

异常处理

使用 try-except 来处理可能发生的异常:

python 复制代码
try:
    response = requests.get('https://httpbin.org/get', timeout=0.01)
except requests.exceptions.Timeout:
    print('Timeout occurred!')
except requests.exceptions.RequestException as e:
    print('Error:', e)

结语

requests 库是 Python 中进行 HTTP 通信的强大工具。它简单、易用,同时功能强大。通过本文,你应该已经能够掌握 requests 的基本用法,并能够将其应用到你的项目中。

参考资料

相关推荐
IVEN_33 分钟前
只会Python皮毛?深入理解这几点,轻松进阶全栈开发
python·全栈
Ray Liang2 小时前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
AI攻城狮2 小时前
如何给 AI Agent 做"断舍离":OpenClaw Session 自动清理实践
python
千寻girling2 小时前
一份不可多得的 《 Python 》语言教程
人工智能·后端·python
AI攻城狮5 小时前
用 Playwright 实现博客一键发布到稀土掘金
python·自动化运维
曲幽6 小时前
FastAPI分布式系统实战:拆解分布式系统中常见问题及解决方案
redis·python·fastapi·web·httpx·lock·asyncio
孟健20 小时前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞1 天前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽1 天前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers