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

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

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


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

相关推荐

python入门到脱坑函数—定义函数_如何定义函数python

Python函数定义:从入门到精通一、函数的基本概念函数是组织好的、可重复使用的代码块,用于执行特定任务。在Python中,函数可以提高代码的模块性和重复利用率。二、定义函数的基本语法def函数名(...

javascript函数的call、apply和bind的原理及作用详解

javascript函数的call、apply和bind本质是用来实现继承的,专业点说法就是改变函数体内部this的指向,当一个对象没有某个功能时,就可以用这3个来从有相关功能的对象里借用过来...

JS中 call()、apply()、bind() 的用法

其实是一个很简单的东西,认真看十分钟就从一脸懵B到完全理解!先看明白下面:例1obj.objAge;//17obj.myFun()//小张年龄undefined例2shows(...

Pandas每日函数学习之apply函数_apply函数python

apply函数是Pandas中的一个非常强大的工具,它允许你对DataFrame或Series中的数据应用一个函数,可以是自定义的函数,也可以是内置的函数。apply可以作用于DataF...

Win10搜索不习惯 换个设定就好了_window10搜索用不了怎么办

Windows10的搜索功能是真的方便,这点用惯了Windows10的小伙伴应该都知道,不过它有个小问题,就是Windows10虽然会自动联网搜索,但默认使用微软自家的Bing搜索引擎和Edge...

面试秘籍:call、bind、apply的区别,面试官为什么总爱问这三位?

引言你有没有发现,每次JavaScript面试,面试官总爱问你call、bind和apply的区别?好像这三个方法成了通关密码,掌握了它们,就能顺利过关。其实不难理解,面试官问这些问题,不...

记住这8招,帮你掌握“追拍“摄影技法—摄影早自习第422日

杨海英同学提问:请问叶梓老师,我练习追拍时,总也不能把运动的人物拍清晰,速度一般掌握在1/40-1/60,请问您如何把追拍拍的清晰?这跟不同的运动形式有关系吗?请您给讲讲要点,谢谢您!摄影:Damia...

[Sony] 有点残酷的测试A7RII PK FS7

都是好机!手中利器!主要是最近天天研究fs5,想知道fs5与a7rii后期匹配问题,苦等朋友的fs5月底到货,于是先拿手里现有的fs7小测一下,十九八九也能看到fs5的影子,另外也了解一下fs5k标配...

AndroidStudio_Android使用OkHttp发起Http请求

这个okHttp的使用,其实网络上有很多的案例的,但是,如果以前没用过,copy别人的直接用的话,可以发现要么导包导不进来,要么,人家给的代码也不完整,这里自己整理一下.1.引入OkHttp的jar...

ESL-通过事件控制FreeSWITCH_es事务控制

通过事件提供的最底层控制机制,允许我们有效地利用工具箱,适时选择使用其中的单个工具。FreeSWITCH是一个核心交换与混合矩阵,它周围有几十个模块提供各种功能特性。我们完全控制了所有的即时信息,这些...

【调试】perf和火焰图_perf生成火焰图

简介perf是linux上的性能分析工具,perf可以对event进行统计得到event的发生次数,或者对event进行采样,得到每次event发生时的相关数据(cpu、进程id、运行栈等),利用这些...

文本检索控件也玩安卓?dtSearch Engine发布Android测试版

dtSearchEngineforLinux(原生64-bit/32-bitC++和JavaAPIs)和dtSearchEngineforWin&.NET(原生64-bi...

网站后台莫名增加N个管理员,记一次SQL注入攻击

网站没流量,但却经常被SQL注入光顾。最近,网站真的很奇怪,网站后台不光莫名多了很多“管理员”,所有的Wordpres插件还会被自动暂停,导致一些插件支持的页面,如WooCommerce无法正常访问、...

多元回归树分析Multivariate Regression Trees,MRT

多元回归树(MultivariateRegressionTrees,MRT)是单元回归树的拓展,是一种对一系列连续型变量递归划分成多个类群的聚类方法,是在决策树(decision-trees)基础...

JMETER性能测试_JMETER性能测试指标

jmeter为性能测试提供了一下特色:jmeter可以对测试静态资源(例如js、html等)以及动态资源(例如php、jsp、ajax等等)进行性能测试jmeter可以挖掘出系统最大能处...