【问题标题】:Web Scraping Returning Empty String网页抓取返回空字符串
【发布时间】:2012-12-25 09:37:15
【问题描述】:

我编写了一些代码来返回和显示this website 上最近的五个帖子。然而,当我使用for 循环运行代码时,会返回一个空字符串。代码如下:

require 'rubygems'
require 'mechanize'

agent = Mechanize.new
site  = "http://metarand.com"
page  = agent.get(site)

for i in 1..5
  puts "#{i}) - #{page.search("#boxes :nth-child(i) .clearfix .blog-title")}"
end

代码有什么问题,我该如何解决?

【问题讨论】:

  • 我只想说,你应该使用.each 而不是forin
  • 我同意@weddingcakes。使用 for 不是惯用的 Ruby。请改用eachfor 可能会产生您所看到的结果。

标签: ruby web screen-scraping mechanize


【解决方案1】:

我相信,你需要这样的东西:

(1..5).each {|i| puts %Q~#{i} - #{page.at("#boxes :nth-child(#{i}) .clearfix .blog-title").text}~  }

【讨论】:

    【解决方案2】:

    简单的错误:

    puts "#{i}) - #{page.search("#boxes :nth-child(i) .clearfix .blog-title")}"
                                                  ^^^
    

    应该是:#{i}

    【讨论】:

      【解决方案3】:
      agent = Mechanize.new
      site  = "http://metarand.com"
      agent.get(site) do |page|
        for i in 1..5
          puts %Q~#{i} - #{page.search("#boxes :nth-child(#{i}) .clearfix .blog-title")}~
        end
      end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-10-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-04
        • 2019-07-07
        • 1970-01-01
        相关资源
        最近更新 更多