本文详细介绍了Python中requests库的基本使用方法,包括如何安装和导入requests库,以及如何使用requests库发送HTTP GET和POST请求。文章还讲解了如何处理请求参数、设置自定义请求头、错误处理和实际案例的应用。requests库是一个功能强大的工具,能够帮助你轻松实现各种网络请求。
Python requests库入门教程 1. 介绍requests库1.1 requests库简介
requests库是Python中最常用的HTTP库之一,它用于发送HTTP请求,并接收响应。requests库简单易用,支持多种HTTP方法,包括GET、POST、PUT、DELETE等。它能够处理几乎所有的HTTP请求,并且提供了丰富的特性,如会话支持、自动解码响应内容、支持HTTPS等。
1.2 安装requests库
要使用requests库,首先需要安装它。可以通过pip工具安装requests库,运行以下命令:
pip install requests
1.3 导入requests库
安装完成后,需要在代码中导入requests库。这可以通过以下代码实现:
import requests
2. 发送HTTP GET请求
2.1 使用requests发送GET请求
发送GET请求是最基本的操作之一。首先,定义请求的目标URL,然后使用requests.get()
方法发送请求。
import requests
url = "https://api.github.com"
response = requests.get(url)
2.2 获取响应内容
发送GET请求后,你会得到一个Response
对象。可以通过response.text
属性获取响应的内容。
print(response.text)
2.3 获取响应头信息
响应头包含了服务器返回的额外信息,如编码格式、服务器类型等。可以通过response.headers
属性获取响应头信息。
print(response.headers)
3. 发送HTTP POST请求
3.1 使用requests发送POST请求
发送POST请求时,通常会携带一些数据。首先,定义请求的目标URL和要发送的数据,然后使用requests.post()
方法发送请求。
import requests
url = "https://httpbin.org/post"
data = {"key1": "value1", "key2": "value2"}
response = requests.post(url, data=data)
3.2 设置请求头和请求体
在发送POST请求时,你可能还需要设置自定义的请求头。这可以通过headers
参数实现:
import requests
url = "https://httpbin.org/post"
data = {"key1": "value1", "key2": "value2"}
headers = {"Content-Type": "application/json"}
response = requests.post(url, data=data, headers=headers)
3.3 处理请求参数
POST请求中,可以传递URL参数。这可以通过params
参数实现:
import requests
url = "https://httpbin.org/post"
params = {"param1": "value1", "param2": "value2"}
data = {"key1": "value1", "key2": "value2"}
response = requests.post(url, params=params, data=data)
4. 处理请求参数和请求头
4.1 URL参数的传递
在GET请求中,经常会传递一些URL参数。这可以通过params
参数实现:
import requests
url = "https://httpbin.org/get"
params = {"param1": "value1", "param2": "value2"}
response = requests.get(url, params=params)
4.2 设置自定义请求头
设置自定义请求头可以对请求进行更细粒度的控制。
import requests
url = "https://httpbin.org/get"
headers = {"Content-Type": "application/json"}
response = requests.get(url, headers=headers)
4.3 处理Cookie和Session
在某些情况下,你可能需要处理Cookie或者使用Session对象来保持会话信息。
4.3.1 使用Cookie
你可以通过cookies
参数传递Cookie。
import requests
url = "https://httpbin.org/get"
cookies = {"cookie1": "value1", "cookie2": "value2"}
response = requests.get(url, cookies=cookies)
4.3.2 使用Session
Session对象可以保持会话信息,适用于需要多次请求的场景。
import requests
url = "https://httpbin.org/get"
session = requests.Session()
cookies = {"cookie1": "value1", "cookie2": "value2"}
response = session.get(url, cookies=cookies)
5. 错误处理
5.1 捕获请求异常
在发送请求时,可能会遇到各种异常,如网络连接失败、请求超时等。可以通过try-except
结构捕获这些异常。
import requests
url = "https://httpbin.org/delay/10"
try:
response = requests.get(url, timeout=5)
except requests.exceptions.Timeout:
print("请求超时")
except requests.exceptions.RequestException as e:
print("请求异常:", e)
5.2 查看错误信息
如果请求失败,可以通过response
对象查看错误信息。
import requests
url = "https://httpbin.org/status/500"
response = requests.get(url)
print("状态码:", response.status_code)
print("错误信息:", response.text)
5.3 重试机制的实现
对于可能失败的请求,可以实现重试机制。这里使用第三方库tenacity
来实现更优雅的重试机制。
import requests
from tenacity import retry, stop_after_attempt, wait_fixed
@retry(stop=stop_after_attempt(3), wait=wait_fixed(2))
def fetch_url(url):
response = requests.get(url, timeout=5)
return response
url = "https://httpbin.org/delay/5"
response = fetch_url(url)
print(response.text)
6. 实际案例
6.1 简单的微博登录模拟
模拟微博登录需要发送登录请求,并处理登录后获取的Cookie。
import requests
url = "https://m.weibo.cn/login"
data = {
"username": "your_username",
"password": "your_password"
}
response = requests.post(url, data=data)
print("登录响应:", response.text)
6.2 获取网页内容并解析
使用requests获取网页内容,并使用BeautifulSoup解析HTML。
import requests
from bs4 import BeautifulSoup
url = "https://www.example.com"
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
title = soup.title.string
print("网页标题:", title)
6.3 使用requests实现文件下载
下载文件通常需要设置适当的请求头,并获取响应的二进制数据。
import requests
url = "https://example.com/file.zip"
response = requests.get(url, stream=True)
with open("file.zip", "wb") as file:
for chunk in response.iter_content(chunk_size=1024):
if chunk:
file.write(chunk)
通过以上内容,我们详细介绍了requests库的基本使用方法,包括发送HTTP请求、处理响应内容、异常处理以及实际案例的应用。requests库是一个非常强大的工具,可以轻松地帮助你实现各种网络请求。
共同學習,寫下你的評論
評論加載中...
作者其他優質文章