在Python中使用mechanize模塊模擬瀏覽器功能
知道如何快速在命令行或者python腳本中實(shí)例化一個(gè)瀏覽器通常是非常有用的。
每次我需要做任何關(guān)于web的自動(dòng)任務(wù)時(shí),我都使用這段python代碼去模擬一個(gè)瀏覽器。
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')]
現(xiàn)在你得到了一個(gè)瀏覽器的示例,br對(duì)象。使用這個(gè)對(duì)象,便可以打開(kāi)一個(gè)頁(yè)面,使用類(lèi)似如下的代碼:
# 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
如果你訪問(wèn)的網(wǎng)站需要驗(yàn)證(http basic auth),那么:
# 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,你不需要管理網(wǎng)站的登錄session。也就是不需要管理需要POST一個(gè)用戶(hù)名和密碼的情況。
通常這種情況,網(wǎng)站會(huì)請(qǐng)求你的瀏覽器去存儲(chǔ)一個(gè)session cookie除非你重復(fù)登陸,
而導(dǎo)致你的cookie中含有這個(gè)字段。所有這些事情,存儲(chǔ)和重發(fā)這個(gè)session cookie已經(jīng)被Cookie Jar搞定了,爽吧。
同時(shí),你可以管理你的瀏覽器歷史:
# 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()
下載一個(gè)文件:
# Download
f = br.retrieve('http://www.google.com.br/intl/pt-BR_br/images/logo.gif')[0]
print f
fh = open(f)
為http設(shè)置代理
# 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")
但是,如果你只想要打開(kāi)網(wǎng)頁(yè),而不需要之前所有神奇的功能,那你可以:
# 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()
你可以通過(guò) mechanize官方網(wǎng)站 , mechanize文檔 和ClientForm的文檔 了解更多。
原文來(lái)自: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/
——————————————————————————————
最后來(lái)聊下通過(guò)代碼訪問(wèn)頁(yè)面時(shí)的一個(gè)很重要的概念和技術(shù):cookie
我們都知道HTTP是無(wú)連接的狀態(tài)協(xié)議,但是客戶(hù)端和服務(wù)器端需要保持一些相互信息,比如cookie,有了cookie,服務(wù)器才能知道剛才是這個(gè)用戶(hù)登錄了網(wǎng)站,才會(huì)給予客戶(hù)端訪問(wèn)一些頁(yè)面的權(quán)限。
比如用瀏覽器登錄新浪微博,必須先登錄,登陸成功后,打開(kāi)其他的網(wǎng)頁(yè)才能夠訪問(wèn)。用程序登錄新浪微博或其他驗(yàn)證網(wǎng)站,關(guān)鍵點(diǎn)也在于需要保存cookie,之后附帶cookie再來(lái)訪問(wèn)網(wǎng)站,才能夠達(dá)到效果。
這里就需要Python的cookielib和urllib2等的配合,將cookielib綁定到urllib2在一起,就能夠在請(qǐng)求網(wǎng)頁(yè)的時(shí)候附帶cookie。
具體做法,首先第一步,用firefox的httpfox插件,在瀏覽器衷開(kāi)始瀏覽新浪微博首頁(yè),然后登陸,從httpfox的記錄中,查看每一步發(fā)送了那些數(shù)據(jù)請(qǐng)求了那個(gè)URL;之后再python里面,模擬這個(gè)過(guò)程,用urllib2.urlopen發(fā)送用戶(hù)名密碼到登陸頁(yè)面,獲取登陸后的cookie,之后訪問(wèn)其他頁(yè)面,獲取微博數(shù)據(jù)。
cookielib模塊的主要作用是提供可存儲(chǔ)cookie的對(duì)象,以便于與urllib2模塊配合使用來(lái)訪問(wèn)Internet資源。例如可以利用本模塊的CookieJar類(lèi)的對(duì)象來(lái)捕獲cookie并在后續(xù)連接請(qǐng)求時(shí)重新發(fā)送。coiokielib模塊用到的對(duì)象主要有下面幾個(gè):CookieJar、FileCookieJar、MozillaCookieJar、LWPCookieJar。
urllib模塊和urllib模塊類(lèi)似,用來(lái)打開(kāi)URL并從中獲取數(shù)據(jù)。與urllib模塊不同的是,urllib模塊不僅可以使用urlopen()函數(shù)還可以自定義Opener來(lái)訪問(wèn)網(wǎng)頁(yè)。同時(shí)要注意:urlretrieve()函數(shù)是urllib模塊中的,urllib2模塊中不存在該函數(shù)。但是使用urllib2模塊時(shí)一般都離不開(kāi)urllib模塊,因?yàn)镻OST的數(shù)據(jù)需要使用urllib.urlencode()函數(shù)來(lái)編碼。
cookielib模塊一般與urllib2模塊配合使用,主要用在urllib2.build_oper()函數(shù)中作為urllib2.HTTPCookieProcessor()的參數(shù)。使用方法如下面登錄人人網(wǎng)的代碼:
#! /usr/bin/env python
#coding=utf-8
import urllib2
import urllib
import cookielib
data={"email":"用戶(hù)名","password":"密碼"} #登陸用戶(hù)名和密碼
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")
具體請(qǐng)參考:
http://www.crazyant.net/796.html Python使用cookielib和urllib2模擬登陸新浪微博并抓取數(shù)據(jù)
http://my.oschina.net/duhaizhang/blog/69342 urllib2模塊
https://docs.python.org/2/library/cookielib.html cookielib — Cookie handling for HTTP clients
- Python使用Selenium模擬瀏覽器自動(dòng)操作功能
- python爬蟲(chóng)模擬瀏覽器訪問(wèn)-User-Agent過(guò)程解析
- python爬蟲(chóng)模擬瀏覽器的兩種方法實(shí)例分析
- 在python中使用requests 模擬瀏覽器發(fā)送請(qǐng)求數(shù)據(jù)的方法
- Python模擬瀏覽器上傳文件腳本的方法(Multipart/form-data格式)
- Python實(shí)現(xiàn)模擬瀏覽器請(qǐng)求及會(huì)話(huà)保持操作示例
- Python模擬鼠標(biāo)點(diǎn)擊實(shí)現(xiàn)方法(將通過(guò)實(shí)例自動(dòng)化模擬在360瀏覽器中自動(dòng)搜索python)
- Python使用win32com實(shí)現(xiàn)的模擬瀏覽器功能示例
- 基于Python模擬瀏覽器發(fā)送http請(qǐng)求
相關(guān)文章
Python實(shí)現(xiàn)提取和去除數(shù)據(jù)中包含關(guān)鍵詞的行
這篇文章主要介紹了Python如何提取數(shù)據(jù)中包含關(guān)鍵詞的行已經(jīng)如何去除數(shù)據(jù)中包含關(guān)鍵詞的行,文中的示例代碼講解詳細(xì),需要的可以參考一下2023-08-08
python封裝對(duì)象實(shí)現(xiàn)時(shí)間效果
這篇文章主要為大家詳細(xì)介紹了python封裝對(duì)象實(shí)現(xiàn)時(shí)間效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2010-10-10
Django User 模塊之 AbstractUser 擴(kuò)展詳解
這篇文章主要介紹了Django User 模塊之 AbstractUser 擴(kuò)展詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-03-03
Python使用django搭建web開(kāi)發(fā)環(huán)境
這篇文章主要為大家詳細(xì)介紹了Python使用django搭建web開(kāi)發(fā)環(huán)境,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-06-06
python實(shí)現(xiàn)一組典型數(shù)據(jù)格式轉(zhuǎn)換
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)一組典型數(shù)據(jù)格式轉(zhuǎn)換,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-12-12
Python?中如何使用requests模塊發(fā)布表單數(shù)據(jù)
requests 庫(kù)是 Python 的主要方面之一,用于創(chuàng)建對(duì)已定義 URL 的 HTTP 請(qǐng)求,本篇文章介紹了 Python requests 模塊,并說(shuō)明了我們?nèi)绾问褂迷撃K在 Python 中發(fā)布表單數(shù)據(jù),感興趣的朋友跟隨小編一起看看吧2023-06-06

