萬盛學電腦網

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

Python 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())

HTTP 基本認證


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")

Cookie 自動管理

掛載 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。

copyright © 萬盛學電腦網 all rights reserved