2011-07-14 74 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