Skip to content

About

Python 的“requests”库:学习 HTTP 方法、响应解析、代理使用、超时设置等知识,实现高效的网页爬虫。

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

1 Commit

Folders and files

NameName
Last commit message
Last commit date
 
 

Repository files navigation

Python Requests 库完整指南

Bright Data 推广

本教程介绍如何在 Python 中使用 Requests 库进行网页爬虫:

Requests 库简介

Requests 是一款简洁易用的 Python HTTP 工具包。具体来说,它提供了直观的 API,让你能够以简单易懂的方式发出 HTTP 请求并处理响应。Requests 在 GitHub 上拥有超过 5 万颗星,每日下载量达数百万次,是 Python 中最受欢迎的 HTTP 客户端。

该库的一些主要功能包括:涵盖所有 HTTP 方法的全面 API、处理服务器响应、自定义请求、登录机制、处理安全证书等。此外,Python Requests 模块原生支持 HTTP/1.1。

设置

安装 Requests 最简单且推荐的方式是使用 pip。具体来说,与 Requests 库对应的 pip 软件包是 requests。因此,你可以使用以下命令安装该 HTTP 客户端:

pip install requests

要在 Python 脚本中使用 requests,请通过以下代码行将其导入:

import requests

太棒了!Requests 软件包现已安装完毕,可以开始使用。

使用场景

Python requests 库的主要使用场景包括:

  • 向 Web 服务器发出 HTTP 请求:通过发送 GET 请求从 Web 服务器检索数据。
  • 调用 API:向 API 端点发送请求并处理响应,从而与各种 Web 服务交互并访问其数据。
  • 网页爬虫:获取与网页关联的 HTML 文档,然后可以使用 BeautifulSoup 等库进行解析,以提取特定信息。
  • 测试 Web 应用程序:模拟 HTTP 请求并验证响应,实现测试流程自动化,确保 Web 服务正常运行。
  • 下载文件:通过向相应 URL 发送 HTTP GET 请求,从 Web 服务器检索图像、文档或其他媒体文件。

方法

下表列出了 requests 库公开提供的方法:

方法 说明
requests.request() 使用指定方法向给定 URL 发送自定义 HTTP 请求
requests.get() 向指定 URL 发送 GET 请求
requests.post() 向指定 URL 发送 POST 请求
requests.put() 向指定 URL 发送 PUT 请求
requests.patch() 向指定 URL 发送 PATCH 请求
requests.delete() 向指定 URL 发送 DELETE 请求
requests.head() 向指定 URL 发送 HEAD 请求

这些方法涵盖了最实用的 HTTP 请求方法。你可以在官方 API 文档中进一步了解如何使用它们。

HTTP 方法

了解 requests Python 库如何处理 HTTP 中的 GET、POST、PUT、DELETE 和 HEAD 方法。

GET

在 HTTP 中,GET 方法用于从服务器请求特定资源。以下是使用 requests.get() 发出 HTTP GET 请求的方法:

import requests

# send a GET request to the specified URL

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

你也可以使用 requests.request() 实现相同结果,如下所示:

import requests

response = requests.request('GET', 'https://api.example.com/data')

在这种情况下,你需要通过额外的字符串变量手动指定要使用的 HTTP 方法。

POST

HTTP POST 方法用于向服务器提交数据,以便进行后续处理。以下是使用 requests.post() 发出 POST 请求的方法:

import requests

# data to be sent in the POST request

product = {

'name': 'Limitor 500',

'description': 'The Limitor 500 is a high-performance electronic device designed to regulate power consumption in industrial settings. It offers advanced features such as real-time monitoring, adjustable settings, and remote access for efficient energy management.',

'price': 199.99,

'manufacturer': 'TechCorp Inc.',

'category': 'Electronics',

'availability': 'In Stock'

}

# send a POST request to the specified URL

response = requests.post('https://api.example.com/product', data=product)

与 GET 请求相比,这次你还需要通过 data 选项指定要发送到服务器的数据。requests 会将这些数据添加到 HTTP 请求正文中。

对于 JSON 正文,请将数据对象传递给 json 选项,而不是 data:

response = requests.post('https://api.example.com/product', json=product)

同样,你可以使用 request.request() 发出相同的请求,如下所示:

import requests

product = {

'name': 'Limitor 500',

'description': 'The Limitor 500 is a high-performance electronic device designed to regulate power consumption in industrial settings. It offers advanced features such as real-time monitoring, adjustable settings, and remote access for efficient energy management.',

'price': 199.99,

'manufacturer': 'TechCorp Inc.',

'category': 'Electronics',

'availability': 'In Stock'

}

response = requests.request('POST', 'https://api.example.com/product', data=product)

PUT

PUT 方法用于更新或替换服务器上的资源。使用 Python requests 模块发送 PUT 请求非常简单,其模式与 POST 请求类似。不同之处在于,要使用的方法是 requests.put()。此外,requests.request() 中的 HTTP 方法字符串应为 'PUT'。

PATCH

PATCH 方法用于对在线资源进行部分修改。与 PUT 请求一样,在 Python requests 库中发送 PATCH 请求与发送 POST 请求类似。不同之处在于,要使用的方法是 requests.patch(),而 requests.request() 中的 HTTP 方法字符串应为 'PATCH'。

DELETE

DELETE 方法用于删除由给定 URI 标识的资源。以下是在 requests 中使用 delete() 方法发出 HTTP DELETE 请求的方式:

import requests

# send a DELETE request for the product with id = 75

response = requests.delete('https://api.example.com/products/75')

同样,你也可以使用 requests.request() 发出 DELETE 请求:

import requests

response = requests.request('DELETE', 'https://api.example.com/products/75')

HEAD

HEAD 方法与 GET 类似,但它只请求响应标头,不包含实际的正文内容。因此,服务器针对 HEAD 请求返回的响应与 GET 请求的响应相同,但不包含正文数据。

使用 requests.head() 在 Python 中发出 HTTP HEAD 请求:

import requests

# send a HEAD request to the specified URL

response = requests.head('https://api.example.com/resource')

同样,你可以使用 requests.request() 发出 HEAD 请求:

import requests

response = requests.request('HEAD', 'https://api.example.com/resource')

解析 Requests 的响应对象

下面来了解如何处理响应对象。

响应对象

发出 HTTP 请求后,requests 会接收服务器响应,并将其映射为一个特殊的 Response 对象。

请看下面的 Python requests 示例:

import requests

response = requests.get('http://lumtest.com/myip.json')

print(response)

它将返回:

<Response [200]>

response 是一个 Response 对象,提供了一些实用的方法和属性。接下来几节将介绍其中最重要的部分!

警告:requests 并不总能返回响应。发生错误时(例如 URL 无效),它会抛出 RequestException。请使用以下逻辑处理此异常:

try:

response = requests.get('http://lumtest.com/myip.json')

# handle the response

except requests.exceptions.RequestException as e:

print('An error occurred during the request:', e)

状态码

响应状态码是服务器返回的标准化值,用于表示请求成功、失败或其他状态。

它们对于错误处理尤其有用,可让客户端识别并妥善处理不同类型的错误。例如,4xx 状态码表示客户端错误(例如请求无效),而 5xx 状态码表示服务器端错误。

使用 requests 库在 Python 中处理响应时,检查状态码通常是第一步。发出请求后,你应始终检查响应状态码,以确定请求是否成功。可以通过响应对象的 status_code 属性访问状态码:

response.status_code # 200

你应根据收到的状态码使用条件语句,妥善处理不同的情况:

import requests

response = requests.get('http://lumtest.com/myip.json')

# check if the request was successful (status code 200)

if response.status_code == 200:

print('Successful request!')

# handle the response...

elif response.status_code == 404:

print('Resource not found!')

else:

print(f'Request failed with status code: {response.status_code}')

在大多数场景中,你只需区分成功请求和错误响应。借助自定义的 __bool()__ 重载,requests 简化了这一过程。具体而言,你可以直接在条件表达式中使用 Response 对象。如果状态码介于 200 和 399 之间,表达式的计算结果为 True;否则为 False。

换句话说,你可以使用以下逻辑检查请求是否成功:

if response:

print('Successful request!')

# handle the response...

else:

print(f'Request failed with status code: {response.status_code}')

响应标头

通过 headers 属性访问服务器响应的标头:

import requests

response = requests.get('http://lumtest.com/myip.json')

response_headers = response.headers

print(response_headers)

这将输出:

{'Server': 'nginx', 'Date': 'Thu, 09 May 2024 12:51:08 GMT', 'Content-Type': 'application/json; charset=utf-8', 'Content-Length': '279', 'Connection': 'keep-alive', 'Cache-Control': 'no-store', 'Access-Control-Allow-Origin': '*'}

如你所见,response.headers 返回一个类似字典的对象。这意味着你可以通过键访问标头值。例如,假设你想访问响应的 Content-Type 标头。可以按以下方式操作:

response_headers['Content-Type'] # 'application/json; charset=utf-8'

由于 HTTP 规范规定标头不区分大小写,因此 requests 允许你直接访问标头,而无需考虑大小写:

response_headers['content-type'] # 'application/json; charset=utf-8'

响应内容

requests 提供了不同的属性和方法来访问响应的有效负载:

以下示例展示了它们的实际用法:

import requests

response = requests.get('http://lumtest.com/myip.json')

# access the response as bytes

response_bytes = response.content

print(type(response_bytes))

print(response_bytes)

print()

# retrieve the response as text

response_text = response.text

print(type(response_text))

print(response_text)

print()

# retrieve the response as a JSON-encoded dictionary

response_json = response.json()

print(type(response_json))

print(response_json)

print()

http://lumtest.com/myip.json 是一个特殊端点,会返回调用方的 IP 信息。上述代码片段的结果大致如下:

<class 'bytes'>

b'{"ip":"45.85.135.110","country":"US","asn":{"asnum":62240,"org_name":"Clouvider Limited"},"geo":{"city":"Ashburn","region":"VA","region_name":"Virginia","postal_code":"20149","latitude":39.0469,"longitude":-77.4903,"tz":"America/New_York","lum_city":"ashburn","lum_region":"va"}}'

<class 'str'>

{"ip":"45.85.135.110","country":"US","asn":{"asnum":62240,"org_name":"Clouvider Limited"},"geo":{"city":"Ashburn","region":"VA","region_name":"Virginia","postal_code":"20149","latitude":39.0469,"longitude":-77.4903,"tz":"America/New_York","lum_city":"ashburn","lum_region":"va"}}

<class 'dict'>

{'ip': '45.85.135.110', 'country': 'US', 'asn': {'asnum': 62240, 'org_name': 'Clouvider Limited'}, 'geo': {'city': 'Ashburn', 'region': 'VA', 'region_name': 'Virginia', 'postal_code': '20149', 'latitude': 39.0469, 'longitude': -77.4903, 'tz': 'America/New_York', 'lum_city': 'ashburn', 'lum_region': 'va'}}

请注意这三种不同的响应格式。作为字典,response.json() 尤其实用,因为它简化了数据访问:

response_json['country'] # 'US'

如需了解更多信息,请查看我们的如何在 Python 中解析 JSON指南。

响应 Cookie

虽然 HTTP Cookie 通过标头定义,但 Response 对象提供了专用的 cookies 属性来处理它们。该属性会返回一个 http.cookiejar 对象,其中包含服务器返回的 Cookie。

下面的示例展示了如何在 Python requests 库中访问响应对象的 Cookie:

import requests

# define the login credentials

credentials = {

'username': 'example_user',

'password': 'example_password'

}

# send a POST request to the login endpoint

response = requests.post('https://www.example.com/login', data=credentials)

# access the cookies set by the server

cookies = response.cookies

# print the cookies received from the server

for cookie in cookies:

print(cookie.name, ':', cookie.value)

上述示例代码片段可能会产生类似以下的结果:

session_id : be400765483cf840dfbbd39

user_id : 7164

expires : Sat, 01 Jan 2025 14:30:00 GMT

使用 Python Requests 库自定义请求

HTTP 请求通常涉及特殊的筛选参数和自定义标头。下面来看看如何在 requests 中指定它们。

查询字符串参数

查询参数也称为 URL 参数,是在 HTTP 请求中附加到 URL 末尾的额外参数。它们向服务器提供有关请求的额外信息,通常用于说明如何筛选数据和自定义响应。

请看以下 URL:

https://api.example.com/data?key1=value1&key2=value2

在此示例中,?key1=value1&key2=value2 是查询字符串,而 key1 和 key2 是查询参数。

查询字符串以 ? 开头,由通过等号(=)分隔的键值对组成,各键值对之间使用 & 连接。在 Python 代码中以编程方式指定此查询字符串并不总是容易,尤其是在处理可选参数时。因此,requests 提供了 params 选项:

import requests

# define query parameters as a dictionary

params = {

'page': 1,

'limit': 10,

'category': 'electronics'

}

# send a GET request to the following URL:

# 'https://api.example.com/products?page=1&limit=10&category=electronics'

response = requests.get('https://api.example.com/products', params=params)

同样,你可以将参数作为元组列表传递给 requests:

import requests

# define query parameters as a list of tuples

params = [

('page', '1'),

('limit', '10'),

('category', 'electronics')

]

response = requests.get('https://api.example.com/products', params=params)

也可以作为 bytes 字符串传递:

import requests

# define query parameters as a bytes string

params = b'page=1&limit=10&category=electronics'

response = requests.get('https://api.example.com/products', params=params)

请求标头

要在 requests 中自定义 HTTP 请求的标头,请将它们作为字典传递给 headers 选项。例如,你可以通过以下方式在 requests 中设置自定义 User-Agent 字符串:

import requests

# define custom headers

custom_headers = {

'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36',

# other headers...

}

# send a GET request with custom headers

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

请求 Cookie

虽然 HTTP Cookie 通过标头发送到服务器,但 requests 提供了专用的 cookies 选项来自定义它们。请参考以下示例:

# define custom cookies

custom_cookies = {

'session_id': 'be400765483cf840dfbbd39',

'user_id': '7164'

}

# send a GET request with custom cookies

response = requests.get('https://www.example.com', cookies=custom_cookies)

请注意,cookies 接受字典或 http.cookiejar 对象。

其他配置

request 提供了丰富的 API,并支持许多高级技巧。下面来了解其中一些最实用的技巧!

代理设置

通过在 requests 中集成代理,你可以经由代理服务器路由 HTTP 请求。这是一种隐藏 IP 地址、绕过速率限制或访问受地理位置限制内容的强大机制。

你可以使用 proxies 选项,将代理服务器与 Python requests 库集成:

import requests

# define the proxy settings

proxy = {

'http': 'http://username:password@proxy.example.com:8080',

'https': 'https://username:password@proxy.example.com:8080'

}

# Make a request using the proxy

response = requests.get('https://www.example.com', proxies=proxy)

如需完整教程,请阅读我们的在 Python Requests 中使用代理指南。

基本身份验证

HTTP 登录机制通常称为“基本登录机制”,是 HTTP 协议内置的一种简单登录机制方案。它会在 Authorization 标头中发送以 Base64 格式编码的用户名和密码。

虽然你可以通过手动设置 Authorization 标头来实现此功能,但 requests 为此提供了专用的 auth 选项。该选项接受包含用户名和密码的元组。你可以使用它在 requests Python 库中处理基本登录机制:

import requests

# define the username and password for basic login mechanisms

username = 'sample_username'

password = 'sample_password'

# send a GET request with basic login mechanisms

response = requests.get('https://api.example.com/private/users', auth=(username, password))

SSL 证书验证

SSL 证书验证对于确保客户端与服务器通过互联网进行安全通信至关重要。不过,有时你信任目标服务器,并不需要强制执行验证。

特别是在通过代理服务器路由 HTTP 流量时,你可能会遇到与 SSL 证书相关的错误。在这种情况下,你可能需要禁用 SSL 证书验证。在 requests 中,可以通过 verify 选项实现:

import requests

# send a GET request to a website with SSL certificate verification disabled

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

超时

默认情况下,requests 会无限期等待服务器响应。如果服务器过载或网络速度变慢,这种行为可能会造成问题。

为了避免应用程序因等待一个可能永远不会到达的响应而变慢,requests 提供了 timeout 选项。该选项接受一个整数或浮点数,表示等待响应的秒数:

import requests

# timeout after 2 second

response1 = requests.get("https://api.example.com/data", timeout=2)

此外,timeout 还接受包含两个元素的元组:连接超时和读取超时。请按以下示例指定它们:

import requests

# timeout after 2.5 seconds for connections and 4 seconds for reading response

response = requests.get("https://api.example.com/data", timeout=(2.5, 4))

如果请求在指定的连接超时时间内建立连接,并在读取超时时间内收到数据,则会照常返回响应。否则,如果请求超时,则会抛出 Timeout 异常:

import requests

from requests.exceptions import Timeout

try:

response = requests.get("https://api.example.com/data", timeout=(2.5, 4))

except Timeout:

print("The request timed out")

总结

Python requests 模块是一个实用且广受欢迎的 HTTP 库,可满足多种使用场景。不过,任何 HTTP 请求都会暴露你的公网 IP。这可能泄露你的身份和所在地信息,不利于保护隐私。

隐藏 IP 地址的方法有很多,而提高安全性和隐私保护效果最有效的方法是使用代理服务器。Bright Data 拥有全球领先的代理服务器,为《财富》500 强企业及超过 20,000 家客户提供服务。

立即注册并开始免费试用!

About

Python 的“requests”库:学习 HTTP 方法、响应解析、代理使用、超时设置等知识,实现高效的网页爬虫。

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors