Ruby Mechanize:关注链接

时间:2011-07-14 06:37:21

标签: ruby mechanize-ruby

在Ruby上的Mechanize中,我必须为每个新页面分配一个新变量。例如:

  page2 = page1.link_with(:text => "Continue").click
  page3 = page2.link_with(:text => "About").click
  ...etc

有没有办法在没有变量保持每个页面状态的情况下运行Mechanize?像

  my_only_page.link_with(:text => "Continue").click!
  my_only_page.link_with(:text => "About").click!

1 个答案:

答案 0 :(得分:10)

我不知道我是否正确理解了你的问题,但是如果要动态地循环遍历大量页面并处理它们,你可以这样做:

    require 'mechanize'

    url = "http://example.com"
    agent = Mechanize.new
    page = agent.get(url) #Get the starting page

    loop do
      # What you want to do on the page - ex. extract something...
      item = page.parser.css('.some_item').text
      item.save

      if link = page.link_with(:text => "Continue") # As long as there is still a nextpage link...
        page = link.click
      else # If no link left, then break out of loop
        break
      end
    end