Web Scraping返回空字符串

时间:2012-12-25 09:37:15

标签: ruby web screen-scraping mechanize

我写了一些代码来返回并显示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

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

3 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

简单的错误:

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

应该是:#{i}