初學者指南:全面了解 Python 的 requests 套件

更新日期: 2025 年 3 月 3 日

在現代的網路應用程式開發中,與網路資源互動是不可或缺的一部分。

不論是抓取網頁數據 (Web Scraping)、調用 API、或是進行各種網路請求 (HTTP Requests),都需要與伺服器進行資料交換。

在 Python 中,requests 套件以其簡單且強大的特性,成為處理 HTTP 請求的首選工具之一。

本篇文章將為初學者介紹如何使用 requests 套件,從基本操作到進階應用,幫助你快速上手。


什麼是 requests 套件?

requests 是一個第三方的 Python 套件,用於發送 HTTP 請求並接收伺服器的回應。

它支援多種 HTTP 方法 (如 GET、POST、PUT、DELETE 等),並提供簡單的 API,讓開發者能夠輕鬆處理網路通訊,無需處理複雜的底層細節。

主要特性:

  • 簡單易用的 API
  • 支援各類型的 HTTP 方法
  • 支援 URL 參數、請求頭 (Headers)、Cookies 和 Session
  • 自動處理編碼和壓縮格式
  • 支援文件上傳、JSON 資料處理、錯誤處理等

如何安裝 requests 套件?

在使用 requests 套件之前,需要先進行安裝。可以使用 Python 的套件管理工具 pip 來安裝:

pip install requests

成功安裝後,可以在你的 Python 環境中通過以下方式確認是否安裝成功:

import requests
print(requests.__version__)

基本用法介紹

發送 GET 請求

GET 請求主要用於從伺服器獲取資料,例如從 API 獲取 JSON 數據或抓取網頁內容。

import requests

url = "https://jsonplaceholder.typicode.com/posts"
response = requests.get(url)

# 檢查請求是否成功 (狀態碼 200 表示成功)
if response.status_code == 200:
    print(response.text)  # 以文字格式輸出回應內容
    print(response.json()) # 若回應是 JSON 格式,可以直接轉換為字典
else:
    print(f"Request failed with status code {response.status_code}")

小技巧:

  • response.status_code: 回傳 HTTP 狀態碼 (如 200、404、500)。
  • response.text: 以字串形式取得回應內容。
  • response.json(): 直接將 JSON 格式的回應轉換為 Python 字典。

送 POST 請求

POST 請求通常用於將數據傳送到伺服器,例如提交表單或傳送 JSON 數據。

url = "https://jsonplaceholder.typicode.com/posts"
data = {
    "title": "foo",
    "body": "bar",
    "userId": 1
}

response = requests.post(url, json=data)

if response.status_code == 201:
    print("Data posted successfully!")
    print(response.json())
else:
    print("Failed to post data.")

小技巧:

  • 在 POST 請求中,可以使用 json 參數直接傳送 JSON 格式資料,或者使用 data 參數傳送表單數據 (application/x-www-form-urlencoded)。

進階用法

傳遞參數 (Query Parameters)

url = "https://jsonplaceholder.typicode.com/posts"
params = {'userId': 1}

response = requests.get(url, params=params)
print(response.url)  # 查看請求的完整 URL
print(response.json())

這會將參數自動編碼成 https://jsonplaceholder.typicode.com/posts?userId=1

自訂請求頭 (Headers)

有時我們需要模擬特定的用戶端(例如設置 User-Agent)或傳遞授權資訊。

url = "https://httpbin.org/get"
headers = {
    "User-Agent": "Mozilla/5.0",
    "Authorization": "Bearer YOUR_TOKEN"
}

response = requests.get(url, headers=headers)
print(response.json())

處理 Cookies

url = "https://httpbin.org/cookies"
cookies = {"session_id": "12345"}

response = requests.get(url, cookies=cookies)
print(response.json())

超時與錯誤處理

在進行網路請求時,設置超時 (Timeout) 和錯誤處理可以提升程序的穩定性。

try:
    response = requests.get("https://httpbin.org/delay/5", timeout=2)
    response.raise_for_status()  # 檢查回應狀態,非 200-399 會拋出錯誤
except requests.exceptions.Timeout:
    print("Request timed out!")
except requests.exceptions.RequestException as e:
    print(f"An error occurred: {e}")

request 與 fetch 兩者差異

requests 套件在 Python 中的角色,和 fetch 函式在 JavaScript 中的功能非常相似。

兩者都是用來發送 HTTP 請求、接收伺服器回應的工具,常見於與 API 互動或進行網頁爬蟲等應用場景。

兩者對比:

功能requests (Python)fetch (JavaScript)
安裝方式需手動安裝 (pip install requests)內建於瀏覽器 (Node.js 18+ 也內建)
支援的 HTTP 方法GET, POST, PUT, DELETE, PATCH 等GET, POST, PUT, DELETE, PATCH 等
返回資料格式response.text, response.json().text(), .json() (Promise)
支援同步/非同步同步操作 (可搭配 asyncio 實現異步)內建為異步 (返回 Promise)
例外錯誤處理自動處理重導、raise_for_status()需手動處理 .ok 或 .status
進階功能Cookies、Session、Timeout、HeadersRequest/Response 拦截、流处理等

簡單對比示例:

在 Python 中用 requests

import requests

url = "https://jsonplaceholder.typicode.com/posts"
response = requests.get(url)

if response.status_code == 200:
    data = response.json()
    print(data[0])
else:
    print("Request failed")

在 JavaScript 中用 fetch

const url = "https://jsonplaceholder.typicode.com/posts";

fetch(url)
  .then(response => {
    if (!response.ok) {
      throw new Error('Request failed');
    }
    return response.json();
  })
  .then(data => console.log(data[0]))
  .catch(error => console.error(error));

什麼時候選擇 requestsfetch

  • 如果你是做前端開發或在瀏覽器中操作,選擇 fetch 是最佳選擇,因為它內建於瀏覽器且支援 Promise 讓非同步操作更簡潔。
  • 如果你是用 Python 做後端開發資料分析網頁爬蟲,那麼 requests 提供的同步操作和友好的 API 會讓你的工作更加方便。

requestshttpx 兩者差異

特性requestshttpx
同步/非同步只支援同步請求支援同步 (requests.get()) 和非同步 (await httpx.get())
異步支援需搭配 asyncio 和第三方套件(較麻煩)原生支援異步 (內建 async / await)
HTTP/2 支援不支援 (僅限 HTTP/1.1)支援 HTTP/1.1 和 HTTP/2
Cookie 管理使用 requests.Session使用 httpx.Client,並支援更好的 Cookie 管理
流 (Streaming)支援 stream=True 參數同樣支援,但在異步流處理上更強大
Timeout 控制單一整體 timeout (timeout=5)支援細粒度控制 (timeout=5 或 timeout=(5, 10))
HTTP 中介 (Proxy)支援 (proxies 參數)支援,且對於非同步請求的代理更靈活
擴展性 (Plugins)不支援支援事件掛勾 (Event Hooks)、擴展性更好

什麼時候應該用 requests

  • 當你的項目主要是同步程序 (如簡單的 API 請求、自動化腳本)。
  • 如果你是初學者,requests 是更容易上手的選擇,API 簡單、文件友好。
  • 當你不需要 HTTP/2 或是異步功能,requests 已經足夠應付大多數情況。

示例 (同步請求):

import requests

response = requests.get("https://jsonplaceholder.typicode.com/posts")
print(response.json())

什麼時候應該用 httpx

  • 當你的項目需要異步請求 (例如處理大量 API 請求、需要更高的併發性能時)。
  • 當你需要使用 HTTP/2,或是需要在異步環境 (如 FastAPI、asyncio) 中發送請求。
  • 當你需要更多擴展性 (例如自訂中介軟體、事件掛勾)。

示例 (非同步請求):

import httpx
import asyncio

async def fetch_data():
    async with httpx.AsyncClient() as client:
        response = await client.get("https://jsonplaceholder.typicode.com/posts")
        print(response.json())

asyncio.run(fetch_data())

延伸閱讀:Python httpx 完整指南:高效的 HTTP 客戶端

選擇建議

  1. 如果你的應用場景是簡單的同步操作,requests 是好選擇,因為它簡單、穩定、歷史悠久。
  2. 如果你正在構建高性能網路應用 (例如需要大量併發請求的爬蟲、API 數據聚合器),選擇 httpx 會讓你的應用更高效。
  3. 若你的項目中已經在使用 asyncioFastAPI 或其他異步框架,httpx 是更自然的搭配。

小結與建議

requests 套件提供了簡單而強大的 API,讓我們可以輕鬆處理各種 HTTP 請求。

無論是發送 GET 或 POST 請求、處理 JSON 資料、設置請求頭、還是進行錯誤處理,requests 都能夠勝任。

對於初學者而言,熟練掌握這個工具將會大大提高你的網路資料處理效率,特別是在進行數據分析、API 開發和網頁爬蟲時。

希望這篇文章能幫助你快速入門 requests 套件,開啟你的網路數據操作之旅!

Similar Posts

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *