在python中使用mechanize模块模拟浏览器功能

知道如何快速在命令行或者python脚本中实例化一个浏览器通常是非常有用的。
每次我需要做任何关于web的自动任务时,我都使用这段python代码去模拟一个浏览器。

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对象。使用这个对象,便可以打开一个页面,使用类似如下的代码:

# 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),那么:

# 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搞定了,爽吧。
同时,你可以管理你的浏览器历史:

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

下载一个文件:

# download
f = br.retrieve(‘http://www.google.com.br/intl/pt-br_br/images/logo.gif’)[0]
print f
fh = open(f)

为http设置代理

# 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”)

但是,如果你只想要打开网页,而不需要之前所有神奇的功能,那你可以:

# 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()的参数。使用方法如下面登录人人网的代码:

#! /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”)

具体请参考:

http://www.crazyant.net/796.html python使用cookielib和urllib2模拟登陆新浪微博并抓取数据

http://my.oschina.net/duhaizhang/blog/69342 urllib2模块

https://docs.python.org/2/library/cookielib.html cookielib — cookie handling for http clients

Posted in 未分类

发表评论