Python http 與 urllib 網路請求

雖然在現代 Python 開發中,大家多半使用第三方套件如 requestshttpx 來處理網路請求,但了解 Python 內建的 httpurllib 仍非常重要,因為它們是所有請求套件的底層基礎,且在某些環境(限制安裝套件)下是唯一的選擇。

urllib.request:發送 HTTP 請求

urllib.request 用於開啟與讀取 URL。

GET 請求

import urllib.request

url = "https://jsonplaceholder.typicode.com/posts/1"

try:
    with urllib.request.urlopen(url) as response:
        # 讀取內容並解碼
        html = response.read().decode('utf-8')
        print(f"狀態碼: {response.status}")
        print(f"內容: {html[:100]}...")
except Exception as e:
    print(f"發生錯誤: {e}")

POST 請求 (傳送數據)

發送 POST 請求需要將數據編碼為 bytes 並傳入 urlopen

import urllib.request
import urllib.parse
import json

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

# 1. 將字典轉換為 JSON 字串並轉為 bytes
json_data = json.dumps(data).encode('utf-8')

# 2. 建立 Request 物件並設定 Header
req = urllib.request.Request(url, data=json_data, method='POST')
req.add_header('Content-Type', 'application/json; charset=utf-8')

# 3. 發送
with urllib.request.urlopen(req) as response:
    result = response.read().decode('utf-8')
    print(result)

http.server:快速啟動伺服器

有時候你需要在本地端快速分享檔案或預覽靜態網頁,http.server 提供了一個現成的工具。

命令列用法 (最常用)

在終端機輸入以下指令,即可將當前目錄變成一個 Web Server:

python -m http.server 8000

程式碼用法

from http.server import HTTPServer, SimpleHTTPRequestHandler

def run_server(port=8000):
    server_address = ('', port)
    httpd = HTTPServer(server_address, SimpleHTTPRequestHandler)
    print(f"伺服器啟動於 http://localhost:{port}")
    httpd.serve_forever()

# run_server()

urllib.parse:處理 URL 字串

處理 URL 中的參數(Query Parameters)時,這個模組非常實用。

from urllib.parse import urlparse, urlencode, parse_qs

url = "https://www.google.com/search?q=python&hl=zh-TW"

# 解析 URL
parsed = urlparse(url)
print(parsed.scheme) # https
print(parsed.query)  # q=python&hl=zh-TW

# 組合參數
params = {'name': '小明', 'city': '台北'}
query_string = urlencode(params)
print(query_string) # name=%E5%B0%8F%E6%98%8E&city=%E5%8F%B0%E5%8C%97

總結

  • urllib.request:內建的 HTTP 客戶端,適合簡單的請求。
  • urllib.parse:專門處理 URL 的組合、分割與參數編碼。
  • http.server:開發時臨時啟動伺服器的神兵利器。
如果你的專案允許安裝第三方套件,建議在大多數生產環境下使用 requestsFastAPI,因為其語法更容易理解且功能更全面。