Python 2 urllib2 發送 POST 請求標準流程:構建 Request、urlencode 編碼表單資料、HTTPCookieProcessor 自動處理 Cookie、讀取回應。本文提供 Python 3 相容改寫版。
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()
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.urlencode | urllib.parse.urlencode |
| Request 資料 | opener.open(req, data) | Request(url, data=bytes, method='POST') |
| Cookie 處理 | urllib2.HTTPCookieProcessor | http.cookiejar.CookieJar + HTTPCookieProcessor |
| 回應讀取 | response.read() (str) | resp.read().decode() (bytes→str) |
| 超時參數 | 不支援 (需 signal) | opener.open(req, timeout=10) |
import requests
resp = requests.post(url, data=payload, timeout=10)
print(resp.status_code, resp.text)
# 自動處理:編碼、Cookie、重導向、gzip、JSON、Session、連線池
requests 為事實標準庫,除無法安裝第三方套件環境,一律優先使用。