知道如何快速在命令行或者python腳本中實例化一個瀏覽器通常是非常有用的。
每次我需要做任何關于web的自動任務時,我都使用這段python代碼去模擬一個瀏覽器。
import mechanizeimport cookielib# Browserbr = mechanize.Browser()# Cookie Jarcj = cookielib.LWPCookieJar()br.set_cookiejar(cj)# Browser optionsbr.set_handle_equiv(True)br.set_handle_gzip(True)br.set_handle_redirect(True)br.set_handle_referer(True)br.set_handle_robots(False)# Follows refresh 0 but not hangs on refresh > 0br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)# Want debugging messages?#br.set_debug_http(True)#br.set_debug_redirects(True)#br.set_debug_responses(True)# User-Agent (this is cheating, ok?)br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]
現在你得到了一個瀏覽器的示例,br對象。使用這個對象,便可以打開一個頁面,使用類似如下的代碼:
# Open some site, let's pick a random one, the first that pops in mind:r = br.open('http://google.com')html = r.read()# Show the sourceprint html# orprint br.response().read()# Show the html titleprint br.title()# Show the response headersprint r.info()# orprint br.response().info()# Show the available formsfor f in br.forms(): print f# Select the first (index zero) formbr.select_form(nr=0)# Let's searchbr.form['q']='weekend codes'br.submit()print br.response().read()# Looking at some results in link formatfor l in br.links(url_regex='stockrt'): print l
如果你訪問的網站需要驗證(http basic auth),那么:
# If the protected site didn't receive the authentication data you would# end up with a 410 error in your facebr.add_password('http://safe-site.domain', 'username', 'password')br.open('http://safe-site.domain')
由于之前使用了Cookie Jar,你不需要管理網站的登錄session。也就是不需要管理需要POST一個用戶名和密碼的情況。
通常這種情況,網站會請求你的瀏覽器去存儲一個session cookie除非你重復登陸,
而導致你的cookie中含有這個字段。所有這些事情,存儲和重發這個session cookie已經被Cookie Jar搞定了,爽吧。
同時,你可以管理你的瀏覽器歷史:
# Testing presence of link (if the link is not found you would have to# handle a LinkNotFoundError exception)br.find_link(text='Weekend codes')# Actually clicking the linkreq = br.click_link(text='Weekend codes')br.open(req)print br.response().read()print br.geturl()# Backbr.back()print br.response().read()print br.geturl()
下載一個文件:
# Downloadf = br.retrieve('http://www.google.com.br/intl/pt-BR_br/images/logo.gif')[0]print ffh = open(f)
新聞熱點
疑難解答