一文掌握Python中的request库(一文掌握python中的request库有哪些)
liuian 2025-03-20 16:25 8 浏览
为什么使用 requests 模块?
在深入研究细节之前,重要的是要了解为什么 Requests 模块比 urllib 等替代方案更受欢迎:
- 单纯:Requests 模块具有更直接的 API,需要更少的代码行来有效执行 HTTP 请求。
- 会话功能:它支持请求之间的持久会话,这对于涉及同一服务器多个事务的任务至关重要。
- 表单处理:通过其直观的方法,提交表单数据变得简单。
- JSON 响应处理:该库允许轻松检索和管理 JSON 数据,JSON 数据是 Web 数据交换的常用格式。
- 异常处理:它会自动为错误状态代码引发异常,从而促进更好的错误管理和更顺畅的调试过程。
安装request模块
如果你还没有安装 requests 模块,你可以使用 pip 轻松完成:
pip install requests
基本用法
要开始使用 requests 模块,您需要导入它,然后您可以使用其函数发送各种类型的 HTTP 请求。
import requests
发送 GET 请求
以下是发送简单的 GET 请求以从服务器获取数据的方法:
import requests
# The URL to which the GET request will be sent.
url = 'https://api.example.com/data'
# Sending a GET request to the specified URL.
# The 'requests.get' function makes an HTTP GET request to the provided URL and stores the response in the 'response' variable.
response = requests.get(url)
# Printing the text content of the response.
# 'response.text' contains the body of the response from the server, typically in string format.
# This is useful for checking what data the server returned in response to the GET request.
print(response.text)
检查响应
发送请求后,检查响应至关重要:
# Check the HTTP status code of the response.
if response.status_code == 200:
# If the status code is 200, it indicates that the request was successful.
print('The request was successful!')
else:
# If the status code is not 200, the request failed.
# Print the status code to help diagnose the issue.
print('The request failed with status code:', response.status_code)
GET 请求中的查询参数
如果需要使用 GET 请求发送查询参数:
# A dictionary containing query parameters for an HTTP GET request.
# These parameters will be appended to the URL as query strings.
params = {
'key1': 'value1',
'key2': 'value2'
}
# Sending a GET request to the specified URL. The 'params' dictionary is converted into query parameters.
# The Requests library automatically encodes these parameters and appends them to the URL.
response = requests.get(url, params=params)
# Printing the final URL after the query parameters have been appended.
# This is useful for debugging to verify that the URL has been constructed correctly.
print(response.url) # This will show the URL with the appended query parameters.
POST 请求
向服务器发送数据通常是使用 POST 请求完成的。以下是对请求执行此操作的方法:
import requests
# A dictionary containing the login credentials, typically a username and password.
data = {
'username': 'john',
'password': 'secret'
}
# Sending a POST request to the login endpoint of the API.
# The 'data' dictionary is passed as form-encoded data to the server.
response = requests.post('https://api.example.com/login', data=data)
# Printing the text of the response from the server, which might include details like login status or tokens.
print(response.text)
# A dictionary representing the data of a new article, including its title, content and associated tags.
json_data = {
'title': 'New Article',
'content': 'This is a new article',
'tags': ['python', 'requests']
}
# Sending a POST request to create a new article on the API.
# The 'json_data' dictionary is passed as JSON. The Requests library automatically sets the appropriate headers.
response = requests.post('https://api.example.com/articles', json=json_data)
# Printing the text of the response from the server, which could be details of the newly created article or an error message.
print(response.text)
处理响应内容
了解如何处理不同类型的响应内容至关重要:
# Printing the text content of the response.
# 'response.text' contains the raw string response received from the server.
print(response.text)
# Parsing the JSON response.
# 'response.json()' converts the JSON formatted string in the response to a Python dictionary.
# This method is convenient for handling JSON data, which is common in REST APIs.
data = response.json()
# Printing the converted Python dictionary.
# This displays the JSON data structured as a dictionary, making it easier to access and manipulate specific data fields.
print(data)
结论
Python 的 Requests 库简化了 HTTP 请求,使开发人员能够更轻松地高效处理网络通信。其简单的 API 支持各种任务,从会话管理到 JSON 数据处理,为经常与 Web API 交互的数据工程师和开发人员展示了它的实用性。
本指南仅触及了 Requests 库的皮毛。除了基础知识之外,该库还支持高级功能,例如流式上传、用于跨请求保留设置的会话对象,以及用于对请求处理进行精细控制的自定义适配器实现。
了解和使用请求库可以增强数据管道和 Web 服务交互,确保它们健壮且易于管理。提供的示例突出了它的多功能性和易用性,巩固了它作为任何 Python 开发人员工具包中必不可少的工具的作用。
相关推荐
- GANs为何引爆机器学习?这篇基于TensorFlow的实例教程为你解惑!
-
「机器人圈导览」:生成对抗网络无疑是机器学习领域近三年来最火爆的研究领域,相关论文层出不求,各种领域的应用层出不穷。那么,GAN到底如何实践?本文编译自Medium,该文作者以一朵玫瑰花为例,详细阐...
- 高丽大学等机构联合发布StarGAN:可自定义表情和面部特征
-
原文来源:arXiv、GitHub作者:YunjeyChoi、MinjeChoi、MunyoungKim、Jung-WooHa、SungKim、JaegulChoo「雷克世界」编译:嗯~...
- TensorFlow和PyTorch相继发布最新版,有何变化
-
原文来源:GitHub「机器人圈」编译:嗯~阿童木呀、多啦A亮Tensorflow主要特征和改进在Tensorflow库中添加封装评估量。所添加的评估量列表如下:1.深度神经网络分类器(DNNCl...
- 「2022 年」崔庆才 Python3 爬虫教程 - 深度学习识别滑动验证码缺口
-
上一节我们使用OpenCV识别了图形验证码躯壳欧。这时候就有朋友可能会说了,现在深度学习不是对图像识别很准吗?那深度学习可以用在识别滑动验证码缺口位置吗?当然也是可以的,本节我们就来了解下使用深度...
- 20K star!搞定 LLM 微调的开源利器
-
LLM(大语言模型)微调一直都是老大难问题,不仅因为微调需要大量的计算资源,而且微调的方法也很多,要去尝试每种方法的效果,需要安装大量的第三方库和依赖,甚至要接入一些框架,可能在还没开始微调就已经因为...
- 大模型DeepSeek本地部署后如何进行自定义调整?
-
1.理解模型架构a)查看深度求索官方文档或提供的源代码文件,了解模型的结构、输入输出格式以及支持的功能。模型是否为预训练权重?如果是,可以在预训练的基础上进行微调(Fine-tuning)。是否需要...
- 因配置不当,约5000个AI模型与数据集在公网暴露
-
除了可访问机器学习模型外,暴露的数据还可能包括训练数据集、超参数,甚至是用于构建模型的原始数据。前情回顾·人工智能安全动态向ChatGPT植入恶意“长期记忆”,持续窃取用户输入数据多模态大语言模型的致...
- 基于pytorch的深度学习人员重识别
-
基于pytorch的深度学习人员重识别Torchreid是一个库。基于pytorch的深度学习人员重识别。特点:支持多GPU训练支持图像的人员重识别与视频的人员重识别端到端的训练与评估简单的re...
- DeepSeek本地部署:轻松训练你的AI模型
-
引言:为什么选择本地部署?在AI技术飞速发展的今天,越来越多的企业和个人希望将AI技术应用于实际场景中。然而,对于一些对数据隐私和计算资源有特殊需求的用户来说,云端部署可能并不是最佳选择。此时,本地部...
- 谷歌今天又开源了,这次是Sketch-RNN
-
前不久,谷歌公布了一项最新技术,可以教机器画画。今天,谷歌开源了代码。在我们研究其代码之前,首先先按要求设置Magenta环境。(https://github.com/tensorflow/magen...
- Tensorflow 使用预训练模型训练的完整流程
-
前面已经介绍了深度学习框架Tensorflow的图像的标注和训练数据的准备工作,本文介绍一下使用预训练模型完成训练并导出训练的模型。1.选择预训练模型1.1下载预训练模型首先需要在Tensorf...
- 30天大模型调优学习计划(30分钟训练大模型)
-
30天大模型调优学习计划,结合Unsloth和Lora进行大模型微调,掌握大模型基础知识和调优方法,熟练应用。第1周:基础入门目标:了解大模型基础并熟悉Unsloth等工具的基本使用。Day1:大模...
- python爬取喜马拉雅音频,json参数解析
-
一.抓包分析json,获取加密方式1.抓包获取音频界面f12打开抓包工具,播放一个(非vip)视频,点击“媒体”单击打开可以复制URL,发现就是我们要的音频。复制“CKwRIJEEXn-cABa0Tg...
- 五、JSONPath使用(Python)(json数据python)
-
1.安装方法pipinstalljsonpath2.jsonpath与Xpath下面表格是jsonpath语法与Xpath的完整概述和比较。Xpathjsonpath概述/$根节点.@当前节点...
- Python网络爬虫的时候json=就是让你少写个json.dumps()
-
大家好,我是皮皮。一、前言前几天在Python白银交流群【空翼】问了一个Python网络爬虫的问题,提问截图如下:登录请求地址是这个:二、实现过程这里【甯同学】给了一个提示,如下所示:估计很多小伙伴和...
- 一周热门
-
-
Python实现人事自动打卡,再也不会被批评
-
Psutil + Flask + Pyecharts + Bootstrap 开发动态可视化系统监控
-
一个解决支持HTML/CSS/JS网页转PDF(高质量)的终极解决方案
-
再见Swagger UI 国人开源了一款超好用的 API 文档生成框架,真香
-
【验证码逆向专栏】vaptcha 手势验证码逆向分析
-
网页转成pdf文件的经验分享 网页转成pdf文件的经验分享怎么弄
-
C++ std::vector 简介
-
python使用fitz模块提取pdf中的图片
-
《人人译客》如何规划你的移动电商网站(2)
-
Jupyterhub安装教程 jupyter怎么安装包
-
- 最近发表
- 标签列表
-
- python判断字典是否为空 (50)
- crontab每周一执行 (48)
- aes和des区别 (43)
- bash脚本和shell脚本的区别 (35)
- canvas库 (33)
- dataframe筛选满足条件的行 (35)
- gitlab日志 (33)
- lua xpcall (36)
- blob转json (33)
- python判断是否在列表中 (34)
- python html转pdf (36)
- 安装指定版本npm (37)
- idea搜索jar包内容 (33)
- css鼠标悬停出现隐藏的文字 (34)
- linux nacos启动命令 (33)
- gitlab 日志 (36)
- adb pull (37)
- table.render (33)
- uniapp textarea (33)
- python判断元素在不在列表里 (34)
- python 字典删除元素 (34)
- react-admin (33)
- vscode切换git分支 (35)
- vscode美化代码 (33)
- python bytes转16进制 (35)