Ruby Mechanize:点击链接

发布于 2024-11-19 17:50:26 字数 384 浏览 4 评论 0原文

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

  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!

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

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

落花浅忆 2024-11-26 17:50:26

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

    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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文