Python使用mechanize類比瀏覽器

來源:互聯網
上載者:User

標籤:python   mechanize   

Python使用mechanize類比瀏覽器

之前我使用內建的urllib2類比瀏覽器去進行訪問網頁等操作,很多網站都會出錯誤,還會返回亂碼,之後使用了 mechanize類比瀏覽器,這些情況都沒出現過,真的很好用,這裡向大家推薦一下。
mechanize是對urllib2的部分功能的替換,能夠更好的類比瀏覽器行為,在web存取控制方面做得更全面。

首先從安裝開始吧,以ubuntu系統為例:

python 絕大部分第三方軟體包,都是標準安裝方式,從官網下載之後,解壓到一個檔案夾內,然後在這個檔案夾內執行這個命令就行了:

python setup.py install

官網網址:
http://wwwsearch.sourceforge.net/mechanize/

更方便的方法就是:先安裝easy_install工具:

正常情況下,我們要給Python安裝第三方的擴充包,我們必須下載壓縮包,解壓縮到一個目錄,然後命令列或者終端開啟這個目錄,然後執行
python setup.py install
來進行安裝。
而使用easy_install我們就可以直接命令列執行
easy_install xxx
就把最新版的xxx封裝上去了
所以easy_install就是為了我們安裝第三方擴充包更容易

安裝方法:

首先下載easy_install的安裝包,:
http://pypi.python.org/pypi/setuptools

下載自己對應的版本,windows上面直接運行exe安裝就可以了

linux上面可以直接運行
sh setuptools-0.6c9-py2.4.egg

安裝完成後,easy_install會被自動複製到bin目錄下,也就是我們的PATH路徑下,所以我們在終端中可以直接運行easy_install命令了

在ubuntu下還有簡潔安裝方法:

安裝easy_install的命令如下:

sudo apt-get install python-setuptools

再用easy_install安裝Mechanize,即:

sudo easy_install Mechanize

安裝好之後就可以愉快的使用了,首先是類比一個瀏覽器的代碼:

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://www.baidu.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‘)

另外利用這個方法,儲存和重發這個session cookie已經被Cookie Jar搞定了,並且可以管理瀏覽器曆史:。除此之外還有眾多應用,如下載:

# Downloadf = br.retrieve(‘http://www.google.com.br/intl/pt-BR_br/images/logo.gif‘)[0]print ffh = open(f)

為http設定代理 :

# Proxy and user/passwordbr.set_proxies({"http": "joe:[email protected]:3128"})# Proxybr.set_proxies({"http": "myproxy.example.com:3128"})# Proxy passwordbr.add_proxy_password("joe", "password")

回退(Back):

列印url即可驗證是否回退

    # Back    br.back()    print br.geturl()

類比Google和百度查詢:

即列印和選擇forms,然後填寫相應索引值,通過post提交完成操作
    for f in br.forms():        print f    br.select_form(nr=0)
Google查詢football
    br.form[‘q‘] = ‘football‘    br.submit()    print br.response().read()
百度查詢football
    br.form[‘wd‘] = ‘football‘    br.submit()    print br.response().read()
相應索引值名,可以通過列印查出

更多的資訊大家可以去官網查看

另外使用mechanize類比瀏覽器去不斷訪問網頁是可以刷各種部落格的訪問量的,包括CSDN,我聲明一下,我測試刷了10個訪問就不搞了,畢竟刷訪問量是個很沒品的事情,而且沒什麼意義,好好寫一篇部落格是為了自己總結自己,也是為了協助他人,分享經驗,去追求什麼訪問量,積分是沒有意義的,奉勸大家也不要亂搞。而且這個很容易查的,被查出來的後果可是很嚴重的,簡單指令碼如下,這個是刷一個網頁100次,間隔1秒:

#!/usr/bin/env pythonimport mechanizeimport cookielibfrom time import ctime,sleepdef run():    print ‘start!‘    for i in range(100):        browse()        print "run",i,"times ",ctime()        sleep(1)def browse():    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)    br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)    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‘)]    r = br.open(‘http://www.baidu.com‘)    html = r.read()    #print htmlrun()print "!!!!!!!!!!!!!!!!!!all over!!!!!!!!!!!!!!!!!! \n %s" %ctime()

我還是學生,寫的不好的地方還請多多指正,

轉載請註明出處:

http://blog.csdn.net/sunmc1204953974

Python使用mechanize類比瀏覽器

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.