Ruby Mechanize:点击链接 [英] Ruby Mechanize: Follow a Link
本文介绍了Ruby Mechanize:点击链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Ruby上的Mechanize中,我必须为进入的每个新页面分配一个新变量.例如:
In Mechanize on Ruby, I have to assign a new variable to every new page I come to. For example:
page2 = page1.link_with(:text => "Continue").click
page3 = page2.link_with(:text => "About").click
...etc
有没有一种方法可以在没有变量保存每个页面状态的情况下运行Mechanize?喜欢
Is there a way to run Mechanize without a variable holding every page state? like
my_only_page.link_with(:text => "Continue").click!
my_only_page.link_with(:text => "About").click!
推荐答案
我不知道我是否正确理解了您的问题,但是如果要动态循环浏览许多页面并对其进行处理,就可以做到像这样:
I don't know if I understand your question correctly, but if it's a matter of looping through a lot of pages dynamically and process them, you could do it like this:
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
这篇关于Ruby Mechanize:点击链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文