当前位置: 首页 > news >正文

Python—requests模块

requests 模块是 Python 中一个非常流行的用于发送 HTTP 请求的第三方库。它提供了一个简单且直观的 API 来处理各种 HTTP 请求,如 GET、POST、PUT、DELETE 等。下面是一些关于 requests 模块的基本用法和示例。

安装 requests 模块

首先,你需要安装 requests 模块。如果你还没有安装,可以使用以下命令通过 pip 安装:

pip install requests

基本用法

发送 GET 请求
import requests

response = requests.get('https://api.example.com/data')

# 检查响应状态码
print(response.status_code)

# 获取响应内容(文本形式)
print(response.text)

# 获取响应内容(JSON 格式,如果响应内容是 JSON)
print(response.json())
发送 POST 请求
import requests

url = 'https://api.example.com/submit'
data = {'key1': 'value1', 'key2': 'value2'}

response = requests.post(url, data=data)

print(response.status_code)
print(response.json())
发送带有请求头的请求
import requests

url = 'https://api.example.com/data'
headers = {
    'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
    'Content-Type': 'application/json'
}

response = requests.get(url, headers=headers)

print(response.status_code)
print(response.json())
发送带有查询参数的请求
import requests

url = 'https://api.example.com/search'
params = {'q': 'python requests', 'sort': 'asc'}

response = requests.get(url, params=params)

print(response.url)  # 查看最终的 URL
print(response.json())
处理响应

response 对象包含了很多有用的信息:

  • response.status_code:HTTP 响应状态码。
  • response.text:响应内容的字符串形式。
  • response.json():将响应内容解析为 JSON 对象(如果内容是 JSON 格式)。
  • response.content:响应内容的二进制形式。
  • response.headers:响应头信息。
  • response.cookies:从响应中提取的 cookies。
异常处理

requests 模块还提供了异常处理机制,常见的异常有 requests.exceptions.RequestException,你可以捕获这个异常来处理请求失败的情况:

import requests
from requests.exceptions import RequestException

try:
    response = requests.get('https://api.example.com/data')
    response.raise_for_status()  # 如果响应状态码不是 200,会抛出 HTTPError 异常
    print(response.json())
except RequestException as e:
    print(f"An error occurred: {e}")

高级用法

使用会话(Session)

会话对象允许你跨请求保持某些参数,比如 cookies 和 headers。

import requests

session = requests.Session()

# 设置会话级别的 headers
session.headers.update({'Authorization': 'Bearer YOUR_ACCESS_TOKEN'})

# 发送请求
response = session.get('https://api.example.com/data')
print(response.json())
超时设置

你可以为请求设置超时时间,以防止请求无限期地挂起:

import requests

try:
    response = requests.get('https://api.example.com/data', timeout=5)  # 5 秒超时
    print(response.json())
except requests.exceptions.Timeout:
    print("The request timed out")

总结

requests 模块是一个非常强大且易于使用的 HTTP 客户端库。它简化了发送 HTTP 请求和处理响应的过程,使开发者能够专注于业务逻辑而不是底层的网络细节。通过掌握这些基本用法,你可以轻松地在 Python 应用中集成 HTTP 请求功能。

相关文章:

  • excel导入Mysql中时间格式异常
  • 深度学习笔记—— GRU(Gated Recurrent Unit)
  • 【设计模式精讲】创建型模式之单例模式(饿汉式、懒汉式、双重校验、静态内部类、枚举)
  • Node IO操作
  • 【阮一峰】2.数组
  • vue3 input type=“file” 修改样式
  • 深入理解Zookeeper:分布式系统的协调者
  • 三、Three.js模型对象、材质
  • 网络运维学习笔记 012网工初级(HCIA-Datacom与CCNA-EI)某机构新增:GRE隧道与EBGP实施
  • 16Linux运维网络基础(02网络层次结构)
  • spring注解开发(纯注解开发模式)(2)
  • MobaXterm通过ssh远程连接Ubuntu的方法
  • 【重磅发布】OmniParser V2-开启GUI自动化新时代
  • 【Python爬虫(26)】Python爬虫进阶:数据清洗与预处理的魔法秘籍
  • LeetCode 热题 100_搜索插入位置(63_35_简单_C++)(二分查找)(”>>“ 与 “/” 对比)
  • 3、Kubernetes 集群部署 Prometheus 和 Grafana
  • Ubuntu 中建的mysql数据库使用Navicat for MySQL连接不上
  • 有向图的强连通分量: Kosaraju算法和Tarjan算法详解
  • Flink CDC详解
  • 【Python】迭代器与生成器详解,附代码(可迭代对象、定义、实现方式、区别、使用场景)
  • 网站建设职位名称/代运营网店公司
  • 模板设计建站/商业策划公司十大公司
  • 爱唐山做贡献月评十佳投票网站/百度seo和谷歌seo有什么区别
  • 湖南做电商网站需要什么条件/谷歌广告平台
  • 做旅游网站的产品经理如何/一键seo提交收录
  • android studio官网/网络seo排名