Ruby:Mechanize的使用教程

小技巧


 

  • puts Mechanize::AGENT_ALIASES 能够打印出全部可用的user_agent
  • puts Mechanize.instance_methods(false) 输出Mechanize模块的全部方法
  • puts Mechanize.instance_methods()   输出Mechanize模块的全部方法以及所继承的类的函数

 推荐阅读


 官方文档html

Many Mechanize Examplesruby

模拟Google搜索cookie

使用mechanize分析并批量下载校内网相册照片dom

Mechanize使用手册中文版 函数

Mechanize使用手册英文版 网站

Mechanize模拟天然网页交互一些基本经常使用方法ui


Ruby中实现网页抓取,通常用的是mechanize,使用很是简单。google

安装spa

sudo gem install mechanize

抓取网页.net

require 'rubygems'
require 'mechanize'
agent = Mechanize.new
page = agent.get('http://google.com/')

模拟点击事件

page = agent.page.link_with(:text => 'News').click

模拟表单提交

google_form = page.form('f')
google_form["q"] = 'ruby mechanize'
page = agent.submit(google_form, google_form.buttons.first)
pp page

分析页面,mechanize用的是nokogiri解析网页的,因此能够参照nokogiri的文档

table = page.search('a')
text = table.inner_text
puts text

有几点注意的地方: 若是须要先登陆的网页,那么能够在网站先登陆,登陆后记录JSESSIONID,而后赋值给agent

cookie = Mechanize::Cookie.new("JSESSIONID", "BA58528B76124698AD033EE6DF12B986:-1")
cookie.domain = "datamirror.csdb.cn"
cookie.path = "/"
agent.cookie_jar.add!(cookie)

若是须要保存网页,使用.save_as,(或许save也能够,我没试过)例如

agent.get("http://google.com").save_as

 


转载自:http://www.cnblogs.com/Stoned/archive/2012/02/23/2364389.html 

相关文章
相关标签/搜索