百度360必应搜狗淘宝本站头条
当前位置:网站首页 > IT知识 > 正文

一文掌握Python中的request库(一文掌握python中的request库有哪些)

liuian 2025-03-20 16:25 13 浏览


为什么使用 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 开发人员工具包中必不可少的工具的作用。

相关推荐

【开源推荐】给大家推荐个基于ChatGPT的PHP开发库 openai-php-api

有了这个库大家就可以愉快的使用PHP对接chatGPT的官方接口了,至于对接了官方接口想要做什么就看你自己的啦环境要求PHP7.4或以上composer1.6.5以上支持框架Laravel、Sym...

3个最流行的大模型应用开发框架【LLM】

随着人工智能的能力,特别是大型语言模型(LLM)的不断发展和演变,开发人员正在寻求将AI功能整合到他们的应用程序中。虽然文本完成和摘要等简单任务可以通过直接调用OpenAI或Coher...

都说PHP性能差,但PHP性能真的差吗?

今天本能是想测试一个PDO持久化,会不会带来会话混乱的问题先贴一下PHP代码,代码丑了点,但是坚持能run就行,反正就是做个测试。<?php$dsn='mysql:host=l...

saas介绍和原理 · laravel-独立站-商城SaaS – 湾区梁工

SaaS就是多租户,一个应用可以分给很多用户使用,而应用只需要维护一个。那么应用就需要做好各种资源的隔离(数据库,文件,缓存,队列,后台,命令行等等)。有两种类型的多租户SaaS形式:1,单数据库Sa...

3分钟短文 | Laravel SQL筛选两个日期之间的记录,怎么写?

引言今天说一个细分的需求,在模型中,或者使用laravel提供的EloquentORM功能,构造查询语句时,返回位于两个指定的日期之间的条目。应该怎么写?本文通过几个例子,为大家梳理一下。学习时...

pip 2(根细胞吸收水借助pip2)

pip-h#-helppipdownload#下载.whl文件,然后是可以安装的UV:Python包管理神器-比pip快100倍安装方法Windows:1powershe...

想买《辐射4》的Pip-Boy特别版?那你可得抓紧点

今年秋天玩家就能够玩到《辐射4(Fallout4)》,而且还可以边玩这款游戏边把真实的Pip-Boy穿戴装置套在手上。最近,这款游戏的Pip-Boy特殊版本已经开放玩家在百思买、沃尔玛以及GameS...

PaddleOCR 介绍及部署(paddleocr 安装)

PaddleOCR是由百度飞桨(PaddlePaddle)团队开发的开源OCR工具包,凭借其高精度、多场景适应性和易用性,成为目前最受欢迎的光学字符识别工具之一。以下是其核心特点与技术亮点:一、...

从需求到技术落地:AI产品经理的技术同理心修炼

在当今快速发展的AI时代,产品经理的角色不再局限于需求收集与规划,还需要深入理解技术实现的边界与成本。本文以UnityML-Agents环境配置与寻路Demo实战为例,探讨AI产品经理如何通过亲身体...

在windows上设置python的环境(windows配置python环境)

上文安装好了python,再具体说下python语言的相关环境。#01关于PythonPython是一个高级别的、边运行边解释的、动态类型的编程语言,以简洁的语法、强大的功能和丰富的资源库而闻名。...

uv——Python开发栈中的高效全能小工具

每天写Python代码的同学,肯定都离不开pip、virtualenv、Poetry等基础工具,但是对这些工具可能是又恨又离不开。那么有什么好的替代呢,虫虫今天就给大家介绍一个替代他们的小工具uv,一...

数据驱动型Python应用开发框架:Taipy

1.介绍Taipy是一个用于构建数据驱动应用的Python框架。它允许开发者快速创建交互式数据应用,支持数据可视化、数据处理和自动化工作流。1.1Taipy核心特性低代码/无代码GUI开发数据...

推荐这几个Python实战项目,瞬间读懂Python!

推荐这几个Python实战项目,瞬间读懂Python!Python这玩意儿,说难不难,说简单吧也不是那么容易。我琢磨着,光看书学理论可不行,得动手写点东西才能真正掌握。今儿个我就给大伙儿推荐几个实战项...

Python项目源码加密部署方案(python源码加密工具)

保护Python代码的几种方式对代码进行混淆以降低源码可读性将py文件编译为二进制pyc文件使用Pyinstaller打包源码为二进制可执行文件使用PyArmor加密脚本将py/py...

史上最全!近万字梳理Python 开发必备的 os 模块(建议收藏)

点赞、收藏、加关注,下次找我不迷路一、开篇本文将带你深入探索os模块的核心功能,通过大量实际案例和代码示例,助你彻底掌握这个Python开发的必备神器。全文近万字,建议收藏后慢慢消化,用的时...