萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python urllib2 發送 HTTP POST 請求完整範例

Python 2 urllib2 發送 POST 請求標準流程:構建 Request、urlencode 編碼表單資料、HTTPCookieProcessor 自動處理 Cookie、讀取回應。本文提供 Python 3 相容改寫版。

Python 2 原版 (參考)


import urllib, urllib2

def post(url, data):
    req = urllib2.Request(url)
    data = urllib.urlencode(data)
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())
    response = opener.open(req, data)
    return response.read()

Python 3 標準庫版 (urllib.request)


import urllib.request
import urllib.parse
import http.cookiejar

def post(url, data, headers=None):
    data_bytes = urllib.parse.urlencode(data).encode('utf-8')
    req = urllib.request.Request(url, data=data_bytes, method='POST')
    if headers:
        for k, v in headers.items():
            req.add_header(k, v)

    # Cookie 自動處理
    cookie_jar = http.cookiejar.CookieJar()
    opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cookie_jar))

    with opener.open(req, timeout=10) as resp:
        return resp.read().decode('utf-8', errors='ignore')

# 使用範例
if __name__ == '__main__':
    login_url = 'https://example.com/login'
    payload = {
        'email': 'user@example.com',
        'password': 'secret',
        'autologin': '1',
        'submit': '登入'
    }
    print(post(login_url, payload))

關鍵差異對比

項目Python 2 (urllib2)Python 3 (urllib.request)
編碼函式urllib.urlencodeurllib.parse.urlencode
Request 資料opener.open(req, data)Request(url, data=bytes, method='POST')
Cookie 處理urllib2.HTTPCookieProcessorhttp.cookiejar.CookieJar + HTTPCookieProcessor
回應讀取response.read() (str)resp.read().decode() (bytes→str)
超時參數不支援 (需 signal)opener.open(req, timeout=10)

現代替代:requests 庫 (強烈推薦)


import requests

resp = requests.post(url, data=payload, timeout=10)
print(resp.status_code, resp.text)
# 自動處理:編碼、Cookie、重導向、gzip、JSON、Session、連線池

requests 為事實標準庫,除無法安裝第三方套件環境,一律優先使用。

copyright © 萬盛學電腦網 all rights reserved