mechanize 模擬瀏覽器:表單提交、Cookie、代理、下載完整指南mechanize 是 Python 經典的「無頭瀏覽器」庫,程式化處理 Cookie、重導向、表單、HTTP 認證、代理,適合爬蟲、自動化測試、API 逆向。本文系統介紹核心用法與進階技巧。
import mechanize
import cookielib
br = mechanize.Browser()
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)
# 瀏覽器行為設定
br.set_handle_equiv(True)
br.set_handle_gzip(True)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False) # 忽略 robots.txt
br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)
# 偽裝 User-Agent
br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Firefox/3.0.1')]
r = br.open('https://google.com')
html = r.read() # 或 br.response().read()
print(br.title()) # 頁面標題
print(r.info()) # 回應標頭
for f in br.forms():
print(f) # 列出所有表單
br.select_form(nr=0) # 選第一個表單
br.form['q'] = 'weekend codes' # 填寫欄位
br.submit() # 提交
print(br.response().read())
for l in br.links(url_regex='stockrt'):
print(l)
req = br.click_link(text='Weekend codes')
br.open(req)
print(br.geturl())
br.back() # 返回上一頁
print(br.geturl())
br.add_password('https://safe-site.domain', 'username', 'password')
br.open('https://safe-site.domain')
f = br.retrieve('https://example.com/logo.gif')[0] # 回傳本地暫存檔路徑
with open(f) as fh:
data = fh.read()
# 帶認證代理
br.set_proxies({"http": "joe:password@myproxy.example.com:3128"})
# 無認證代理
br.set_proxies({"http": "myproxy.example.com:3128"})
# 代理密碼單獨設定
br.add_proxy_password("joe", "password")
掛載 cookielib.LWPCookieJar 後,登入時伺服器下發的 Set-Cookie 會自動儲存,後續請求自動帶上,無需手動處理 Session ID。
urllib2 / urllib
# 只需簡單 GET
import urllib2
print(urllib2.urlopen('https://example.com').read())
# 基本認證
import urllib
opener = urllib.FancyURLopener()
print(opener.open('https://user:pass@example.com').read())
| 工具 | 特點 | 適用場景 |
|---|---|---|
mechanize | 高階 API、自動 Cookie/表單、同步 | 傳統爬蟲、表單密集型站點、Python 2 專案 |
requests + requests-html | 人性化 API、支援 JS 渲染 | 現代爬蟲、API 客戶端 |
selenium / playwright | 真實瀏覽器、完整 JS、截圖 | SPA、反爬蟲強、E2E 測試 |
httpx + parsel | 支援 async、HTTP/2、CSS/XPath | 高效能非同步爬蟲 |
mechanize 歷史地位重要,但已停更(最後版 2017),新專案建議用 requests + lxml/parsel 或 httpx + selectolax,若需 JS 則上 playwright。