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

第三方软件测评机构:【Python Requests库实战教学】

Requests 是一个简洁且功能强大的 Python HTTP 库。它是对 Python 标准库中冗长而繁琐的 urllib 模块的封装,是让 HTTP 请求变得异常简单直观,极大地提升了开发效率。

0.Requests安装:
pip install requests
1.GET 请求:获取资源
import requests# 最基本的 GET 请求
response = requests.get('https://zmtests.com/get')# 带参数的 GET 请求 (方式一: 使用 `params` 字典,推荐)
params = {'key1': 'value1', 'key2': 'value2'}
response = requests.get('https://zmtests.com/get', params=params)
# 最终请求的URL将是: https://zmtests.com/get?key1=value1&key2=value2
print(response.url)# 带请求头的 GET 请求 (模拟浏览器)
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
response = requests.get('https://zmtests.com/get', headers=headers)
2.POST 请求:提交数据
import requests
import json# 提交表单数据 (application/x-www-form-urlencoded)
data = {'username': 'admin', 'password': 'secret'}
response = requests.post('https://zmtests.com/post', data=data)# 提交 JSON 数据 (application/json) - 最常用!
json_data = {'title': 'foo', 'body': 'bar', 'userId': 1}
# 方法一: 使用 `json` 参数,Requests 会自动序列化并设置 Content-Type
response = requests.post('https://zmtests.com/post', json=json_data)# 方法二: 手动序列化并设置 headers
headers = {'Content-Type': 'application/json'}
response = requests.post('https://zmtests.com/post', data=json.dumps(json_data), headers=headers)# 上传文件 (multipart/form-data)
files = {'file': ('report.xlsx', open('report.xlsx', 'rb'), 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')}
response = requests.post('https://zmtests.com/post', files=files)
3.其他 HTTP 方法:PUT, DELETE, HEAD, OPTIONS 等方法用法类似。
response = requests.put('https://zmtests.com/put', data={'key': 'value'})
response = requests.delete('https://zmtests.com//delete')
response = requests.head('https://zmtests.com//get')
response = requests.options('https://zmtests.com//get')
4. 处理响应:发起请求后,会返回一个 Response 对象,它包含了服务器返回的所有信息。
import requests
response = requests.get('https://zmtests.com/get')# 状态码 (200 表示成功,404 Not Found, 500 Server Error, etc.)
print(response.status_code)
# 更友好的方式:使用布尔判断
if response.ok: # 状态码在 200 到 400 之间为 Trueprint("请求成功!")# 响应头 (是一个字典,但不区分大小写)
print(response.headers)
print(response.headers['Content-Type'])
print(response.headers.get('content-type')) # 推荐用 get,键不存在时返回 None# 响应内容
# .text: 返回解码后的字符串 (Requests 会自动推测编码)
print(response.text)# .content: 返回原始的 bytes 对象 (用于非文本内容,如图片、文件)
# 例如,下载一张图片:
img_data = requests.get('https://zmtests.com/image/png').content
with open('image.png', 'wb') as f: # 注意是 'wb' 写入二进制模式f.write(img_data)# .json(): 如果响应是 JSON,直接解析成 Python 字典或列表
json_response = response.json()
print(json_response['args']) # 访问解析后的数据# 原始响应(极少用到,用于低级操作)
raw_response = requests.get('https://zmtests.com/get', stream=True)
print(raw_response.raw.read(10))
5.会话对象:保持状态,使用 Session 对象可以在多次请求间自动保持 Cookie、连接和配置(如 Headers)。
import requests# 创建一个会话
s = requests.Session()# 所有通过这个会话发起的请求都会保持 Cookie
# 模拟登录
login_data = {'user': 'admin', 'pass': 'secret'}
s.post('https://zmtests.com/login', data=login_data)# 后续请求会自动携带登录后的 Cookie
response = s.get('https://zmtests.com/dashboard')
# ... 执行其他需要登录状态的操作# 会话也可以设置公共的请求头
s.headers.update({'User-Agent': 'My-Awesome-App/1.0'})
6.超时控制
# 设置一个总的超时时间(连接超时 + 读取超时)
try:response = requests.get('https://zmtests.com/delay/10', timeout=5) # 5秒后超时
except requests.exceptions.Timeout:print("请求超时了!")# 更精细的控制:(连接超时, 读取超时)
response = requests.get('https://zmtests.com/get', timeout=(3.05, 27))
# 3.05秒内必须建立连接,建立连接后27秒内必须返回响应数据
7.异常调试处理
from requests.exceptions import RequestException, Timeout, ConnectionErrortry:response = requests.get('https://www.zmtests.com', timeout=5)response.raise_for_status() # 如果状态码不是200,抛出 HTTPError 异常# ... 处理成功的响应except Timeout:print("请求超时")
except ConnectionError:print("网络连接错误(DNS 失败、拒绝连接等)")
except requests.HTTPError as err:print(f"HTTP 错误: {err}") # 例如 404, 500
except RequestException as err:print(f"未知请求错误: {err}") # 所有Requests异常的基类
8.代理
proxies = {'http': 'http://10.10.1.10:3128', # HTTP 代理'https': 'http://10.10.1.10:1080', # HTTPS 代理 (注意协议是http://)
}# 或者使用 SOCKS 代理 (需要安装 `pip install requests[socks]`)
proxies = {'http': 'socks5://user:pass@host:port','https': 'socks5://user:pass@host:port'
}response = requests.get('https://zmtests.com/ip', proxies=proxies)
9.SSL 证书验证
# 验证 SSL 证书(默认,推荐)
response = requests.get('https://github.com', verify=True)# 忽略 SSL 证书验证(不安全警告!仅用于测试)
response = requests.get('https://self-signed.badssl.com', verify=False)
# 通常会看到警告,可以禁用:
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)# 使用自定义 CA 证书包
response = requests.get('https://github.com', verify='/path/to/certfile.pem')
10. 实战示例:
import requests
from requests.exceptions import HTTPErrorBASE_URL = 'https://jsonplaceholder.zmtests.com'# 1. 创建一个会话
with requests.Session() as s:s.headers.update({'Content-Type': 'application/json; charset=UTF-8'})try:# 2. 获取所有帖子 (GET)print("获取帖子列表...")resp_posts = s.get(f"{BASE_URL}/posts")resp_posts.raise_for_status()posts = resp_posts.json()print(f"获取到 {len(posts)} 篇帖子")# 3. 获取第一篇帖子的详情first_post_id = posts[0]['id']print(f"\n获取第一篇帖子 (ID: {first_post_id}) 的评论...")resp_comments = s.get(f"{BASE_URL}/posts/{first_post_id}/comments")comments = resp_comments.json()print(f"获取到 {len(comments)} 条评论")# 4. 创建一篇新帖子 (POST)print("\n创建一篇新帖子...")new_post_data = {'title': 'My New Post','body': 'This is the body of my new post.','userId': 1}resp_new = s.post(f"{BASE_URL}/posts", json=new_post_data)resp_new.raise_for_status()created_post = resp_new.json()print(f"新帖子创建成功!ID: {created_post['id']}")except HTTPError as err:print(f"HTTP 错误发生: {err}")except Exception as err:print(f"其他错误: {err}")

通过这份Requests 库教学,应该能够使用 Requests 库处理绝大多数 HTTP 交互。记住:使用 Session、总是设置超时、处理异常、谨慎关闭 SSL 验证。


文章转载自:

http://Wkx2Fjgj.zsLtw.cn
http://LQSgg8lU.zsLtw.cn
http://7KaxxYGf.zsLtw.cn
http://N50uisnX.zsLtw.cn
http://MGEeDdXw.zsLtw.cn
http://aDKLXoUP.zsLtw.cn
http://D7dl1Ckt.zsLtw.cn
http://zcqy6Qih.zsLtw.cn
http://JF7IcB1X.zsLtw.cn
http://vtftRyMx.zsLtw.cn
http://eZlYnJlx.zsLtw.cn
http://ECP6gz3V.zsLtw.cn
http://XIzp7XRl.zsLtw.cn
http://cl7CUG8o.zsLtw.cn
http://AdHdYxQq.zsLtw.cn
http://9iDk1QhR.zsLtw.cn
http://GW88irwp.zsLtw.cn
http://VTe1BA4u.zsLtw.cn
http://awsV65nR.zsLtw.cn
http://OiVjUUAF.zsLtw.cn
http://cVQfaloa.zsLtw.cn
http://0U8GNPmG.zsLtw.cn
http://XcImjejn.zsLtw.cn
http://b81Cl4jM.zsLtw.cn
http://R2QSLJgW.zsLtw.cn
http://SwR3D2ld.zsLtw.cn
http://WI0WGB5S.zsLtw.cn
http://TVg4pprY.zsLtw.cn
http://ZP6NneRQ.zsLtw.cn
http://GpEYOASq.zsLtw.cn
http://www.dtcms.com/a/388236.html

相关文章:

  • 信用违约风险分类预测:XGBoost +SHAP实践案例
  • TypeScript 基础
  • 蔡勒公式的介绍
  • 云蝠智能大模型呼叫全栈适配阿里云国产GPU
  • OpenCV与深度神经网络的风格迁移
  • 百度股价突破120美元创年内新高,AI云成为增长新引擎
  • EFFICIENT STREAMING LANGUAGE MODELS WITH ATTENTION SINKS论文阅读
  • Blockview
  • [Dify] Agent 模式下的流程自动化范式解析
  • Java泛型:类型安全的艺术与实践指南
  • React+antd实现监听localStorage变化多页面更新+纯js单页面table模糊、精确查询、添加、展示功能
  • 事件驱动临床系统:基于FHIR R5 SubscriptionsBulk Data的编程实现(中)
  • 电源滤波器如何“滤”出稳定电力
  • 非连续内存分配
  • CKA08--PVC
  • 贪心算法应用:分数背包问题详解
  • What is Vibe Coding? A New Way to Build with AI
  • 【Anaconda_pandas+numpy】the pandas numpy version incompatible in anaconda
  • 【3D点云测量视觉软件】基于HALCON+C#开发的3D点云测量视觉软件,全套源码+教学视频+点云示例数据,开箱即用
  • 卡尔曼Kalman滤波|基础学习(一)
  • MoPKL模型学习(与常见红外小目标检测方法)
  • 数据驱动变革时代,自动驾驶研发如何破解数据跨境合规难题?
  • Cmake总结(上)
  • Linux笔记---非阻塞IO与多路复用select
  • 一文读懂大数据
  • MySQL 多表联合查询与数据备份恢复全指南
  • 简介在AEDT启动前处理脚本的方法
  • Spring 感知接口 学习笔记
  • AI重构服务未来:呼叫中心软件的智能跃迁之路
  • 从食材识别到健康闭环:智能冰箱重构家庭膳食管理