在Python中使用mechanize模組類比瀏覽器功能

來源:互聯網
上載者:User

   這篇文章主要介紹了在Python中使用mechanize模組類比瀏覽器功能,包括使用cookie和設定代理等功能的實現,需要的朋友可以參考下

  知道如何快速在命令列或者python指令碼中執行個體化一個瀏覽器通常是非常有用的。

  每次我需要做任何關於web的自動任務時,我都使用這段python代碼去類比一個瀏覽器。

  ?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 import mechanize import cookielib # Browser br = mechanize.Browser() # Cookie Jar cj = cookielib.LWPCookieJar() br.set_cookiejar(cj) # Browser options 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) # Follows refresh 0 but not hangs on refresh > 0 br.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對象。使用這個對象,便可以開啟一個頁面,使用類似如下的代碼:

  ?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 # 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 source print html # or print br.response().read() # Show the html title print br.title() # Show the response headers print r.info() # or print br.response().info() # Show the available forms for f in br.forms(): print f # Select the first (index zero) form br.select_form(nr=0) # Let's search br.form['q']='weekend codes' br.submit() print br.response().read() # Looking at some results in link format for l in br.links(url_regex='stockrt'): print l

  如果你訪問的網站需要驗證(http basic auth),那麼:

  ?

1 2 3 4 # If the protected site didn't receive the authentication data you would # end up with a 410 error in your face br.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搞定了,爽吧。

  同時,你可以管理你的瀏覽器曆史:

  ?

1 2 3 4 5 6 7 8 9 10 11 12 # 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 link req = br.click_link(text='Weekend codes') br.open(req) print br.response().read() print br.geturl() # Back br.back() print br.response().read() print br.geturl()

  下載一個檔案:

  ?

1 2 3 4 # Download f = br.retrieve('logo.gif')[0] print f fh = open(f)

  為http設定代理

  ?

1 2 3 4 5 6 # Proxy and user/password br.set_proxies({"http": "joe:password@myproxy.example.com:3128"}) # Proxy br.set_proxies({"http": "myproxy.example.com:3128"}) # Proxy password br.add_proxy_password("joe", "password")

  但是,如果你只想要開啟網頁,而不需要之前所有神奇的功能,那你可以:

  ?

1 2 3 4 5 6 7 # Simple open? import urllib2 print urllib2.urlopen('http://stockrt.github.com').read() # With password? import urllib opener = urllib.FancyURLopener() print opener.open('http://user:password@stockrt.github.com').read()

  你可以通過 mechanize官方網站 , mechanize文檔 和ClientForm的文檔 瞭解更多。

  原文來自:http://reyoung.me/index.php/2012/08/08/%E7%BF%BB%E8%AF%91%E4%BD%BF%E7%94%A8python%E6%

A8%A1%E4%BB%BF%E6%B5%8F%E8%A7%88%E5%99%A8%E8%A1%8C%E4%B8%BA/

  ——————————————————————————————

  最後來聊下通過代碼訪問頁面時的一個很重要的概念和技術:cookie

  我們都知道HTTP是不需連線的狀態協議,但是用戶端和伺服器端需要保持一些相互資訊,比如cookie,有了cookie,伺服器才能知道剛才是這個使用者登入了網站,才會給予用戶端訪問一些頁面的許可權。

  比如用瀏覽器登入新浪微博,必須先登入,登陸成功後,開啟其他的網頁才能夠訪問。用程式登入新浪微博或其他驗證網站,關鍵點也在於需要儲存cookie,之後附帶cookie再來訪問網站,才能夠達到效果。

  這裡就需要Python的cookielib和urllib2等的配合,將cookielib綁定到urllib2在一起,就能夠在請求網頁的時候附帶cookie。

  具體做法,首先第一步,用firefox的httpfox外掛程式,在瀏覽器衷開始瀏覽新浪微博首頁,然後登陸,從httpfox的記錄中,查看每一步發送了那些資料請求了那個URL;之後再python裡面,類比這個過程,用urllib2.urlopen發送使用者名稱密碼到登陸頁面,擷取登陸後的cookie,之後訪問其他頁面,擷取微博資料。

  cookielib模組的主要作用是提供可儲存cookie的對象,以便於與urllib2模組配合使用來訪問Internet資源。例如可以利用本模組的CookieJar類的對象來捕獲cookie並在後續串連請求時重新發送。coiokielib模組用到的對象主要有下面幾個:CookieJar、FileCookieJar、MozillaCookieJar、LWPCookieJar。

  urllib模組和urllib模組類似,用來開啟URL並從中擷取資料。與urllib模組不同的是,urllib模組不僅可以使用urlopen()函數還可以自訂Opener來訪問網頁。同時要注意:urlretrieve()函數是urllib模組中的,urllib2模組中不存在該函數。但是使用urllib2模組時一般都離不開urllib模組,因為POST的資料需要使用urllib.urlencode()函數來編碼。

  cookielib模組一般與urllib2模組配合使用,主要用在urllib2.build_oper()函數中作為urllib2.HTTPCookieProcessor()的參數。使用方法如下面登入人人網的代碼:

  ?

1 2 3 4 5 6 7 8 9 10 11 12 13 #! /usr/bin/env python #coding=utf-8 import urllib2 import urllib import cookielib data={"email":"使用者名稱","password":"密碼"} #登陸使用者名稱和密碼 post_data=urllib.urlencode(data) cj=cookielib.CookieJar() opener=urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) headers ={"User-agent":"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1"} req=urllib2.Request("http://www.renren.com/PLogin.do",post_data,headers) content=opener.open(req) print content.read().decode("utf-8").encode("gbk")

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.