首页 > 编程 > Python > 正文

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

2020-02-23 01:06:11
字体:
来源:转载
供稿:网友

知道如何快速在命令行或者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)            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表