0

我写了一些代码来返回和显示这个网站上最近的五个帖子。然而,当我使用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

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

4

3 回答 3

1

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

(1..5).each {|i| puts %Q~#{i} - #{page.at("#boxes :nth-child(#{i}) .clearfix .blog-title").text}~  }
于 2012-12-25T10:14:24.837 回答
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
于 2012-12-25T10:11:34.723 回答
0

简单的错误:

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

应该:#{i}

于 2012-12-25T10:13:45.960 回答