Python 2 使用 urllib 編碼資料,urllib2 發送請求。Python 3 整合為 urllib.request、urllib.parse。本文示範 Python 2 版本發送表單資料並處理 Cookie。
# -*- coding: cp936 -*-
import urllib2
import urllib
def postHttp(name=None, tel=None, address=None, price=None,
num=None, paytype=None, posttype=None, other=None):
url = "https://www.xxx.com/dog.php"
postdata = dict(name=name, tel=tel, address=address, price=price,
num=num, paytype=paytype, posttype=posttype, other=other)
# URL 編碼
postdata = urllib.urlencode(postdata)
# 建立請求(自動加入 Content-Type: application/x-www-form-urlencoded)
request = urllib2.Request(url, postdata)
response = urllib2.urlopen(request)
print(response.read())
# 呼叫範例
postHttp('姓名', '電話', '地址', '230元', '1',
'貨到付款', 'EMS國內郵政特快專遞', '饑渴長耳兔-國際品牌')
import urllib.request
import urllib.parse
def postHttp(**kwargs):
url = "https://www.xxx.com/dog.php"
data = urllib.parse.urlencode(kwargs).encode('utf-8')
req = urllib.request.Request(url, data=data, method='POST')
with urllib.request.urlopen(req) as resp:
print(resp.read().decode('utf-8'))
import urllib2
import cookielib
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
urllib2.install_opener(opener)
# 後續請求自動攜帶/儲存 Cookie
multipart/form-data(需手動構建或用 requests 套件)。urllib2.HTTPError, URLError。requests 套件,API 更簡潔強大。
import requests
resp = requests.post('https://www.xxx.com/dog.php', data=payload)
print(resp.text)
理解底層 urllib 機制有助於除錯,實務開發首選 requests。