2011-07-14 70 views
5

在Mechanize on Ruby中,我必须为每个新页面分配一个新变量。例如:Ruby机械化:遵循链接

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

有没有一种方法来运行机械化没有一个变量持有每个页面状态?像

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

回答

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 
+2

伟大的答案,这也是我一直在寻找的,我拥有它,但是你的代码比我的方法好很多。 – LF4