Home  >  Article  >  Backend Development  >  Python使用Mechanize模块编写爬虫的要点解析

Python使用Mechanize模块编写爬虫的要点解析

WBOY
WBOYOriginal
2016-06-10 15:05:211165browse

 mechanize是对urllib2的部分功能的替换,能够更好的模拟浏览器行为,在web访问控制方面做得更全面。结合beautifulsoup和re模块,可以有效的解析web页面,我比较喜欢这种方法。
    下面主要总结了使用mechanize模拟浏览器的行为和几个例子(谷歌搜索,百度搜索和人人网登录等)
1.初始化并建立一个浏览器对象
    如果没有mechanize需要easy_install安装,以下代码建立浏览器对象并作了一些初始化设置,实际使用过程可以按需开关。其实只用默认的设置也可以完成基本任务。

#!/usr/bin/env python
import sys,mechanize

#Browser
br = mechanize.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)

#debugging?
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')]


2.模拟浏览器行为
    浏览器对象建立并初始化完毕之后即可使用了,下面给出几个例子(代码承接以上部分)
获取web网页:
    分行打印可以逐个查看详细信息,就不赘述

r = br.open(sys.argv[1])
html = r.read()
print html
print br.response().read()
print br.title()
print r.info()


模拟谷歌和百度查询
    打印和选择forms,然后填写相应键值,通过post提交完成操作

for f in br.forms():
 print f

br.select_form(nr=0)

    谷歌查询football

br.form['q'] = 'football'
br.submit()
print br.response().read()


    百度查询football

br.form['wd'] = 'football'
br.submit()
print br.response().read()

  
    相应键值名,可以通过打印查出

回退(Back)
    非常简单的操作,打印url即可验证是否回退

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

3.http基本认证

br.add_password('http://xxx.com', 'username', 'password')
br.open('http://xxx.com')

4.form认证
    以登陆人人网为例,打印forms可以查出用户名和密码键信息

br.select_form(nr = 0)
br['email'] = username
br['password'] = password
resp = self.br.submit()

5.cookie支持
    通过导入cookielib模块,并设置浏览器cookie,可以在需要认证的网络行为之后不用重复认证登陆。通过保存session cookie即可重新访问,Cookie Jar完成了该功能。

#!/usr/bin/env python
import mechanize, cookielib

br = mechanize.Browser()
cj = cookielib.LWPCookieJar()
br.set_cookiejar()

6.proxy设置
设置http代理

#Proxy
br.set_proxies({"http":"proxy.com:8888"})
br.add_proxy_password("username", "password")

#Proxy and usrer/password
br.set_proxies({"http":"username:password@proxy.com:8888"})

7.关于内存过高问题

在用mechanize写了一个爬虫脚本,想要去某网站爬取大概30万张图片。
 
整个过程是:
1、获取目标页面地址
2、取得目标地址前几页的所有图片url
3、对这些url进行下载,并把索引数据保存到mysql数据库。


这个脚本大概每秒钟完成一张图片的下载(主要是网络只有200K/S左右,是瓶颈)
当图片下载到大约15000张左右的时候,发现越来越慢,最后干脆停下了。
用ps aux查看,发现进程sleep了,感觉很奇怪。
free看一下,内存竟然只剩下100M了(系统总内存4GB)
在网上瞎逛了一下,发现原来mechanize默认会保存模拟过的操作历史,导致占用的内存越来越大:
http://stackoverflow.com/questions/2393299/how-do-i-disable-history-in-python-mechanize-module
 
为了方便,大约翻译一下:
mechanize初始化Browser()的时候,如果你不给他传一个history对象作为参数,Browser()就会按照默认的方式(允许保存操作历史)来进行初始化,你可以随便传个什么history给它即可,如自定义一个NoHistory对象:
 

class NoHistory(object): 
 def add(self, *a, **k): pass 
 def clear(self): pass 
 
b = mechanize.Browser(history=NoHistory()) 
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn