http://wwwsearch.sourceforge.net/mechanize/

  http://blog.chinaunix.net/uid-26722078-id-3507409.html

 

  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"})

  • 相关文章:

    • 2022-02-22
    • 2022-12-23
    • 2022-01-04
    • 2021-12-07
    • 2021-12-30
    • 2022-12-23
    • 2021-10-19
    • 2021-04-04
    猜你喜欢
    • 2022-02-05
    • 2021-06-22
    • 2022-02-25
    • 2021-08-09
    • 2021-12-23
    • 2022-02-11
    • 2022-12-23
    相关资源
    相似解决方案