我有以下ruby脚本:

require "rubygems"
require "rest-client" #although not required in the program
require "open-uri"
require "nokogiri"


puts "Opening file"
page=File.open("file.html","r"){|file| file.read}
puts page
    page = Nokogiri::HTML(page)
    puts page.class
    #Filters content of page to select all references to the documents filing date
    td_rows = page.css('td i.blue')
    puts td_rows

我可以从coderunner或textwrangler运行这个脚本,并使用ruby“filename”从终端调用它。不过,我试图让脚本在某个时间点运行,并尝试使用键盘大师或鸭嘴兽调用脚本,但尽管它运行起来,似乎并没有完成这一行
td_rows = page.css('td i.blue')

变量td_rows不包含任何内容有人知道为什么这样不行吗?
非常感谢

最佳答案

如果代码无法读取文件,Nokogiri在尝试分析空字符串时仍将创建空HTML文档:

[2] (pry) main: 0> Nokogiri::HTML('')
=> #(Document:0x245962c {
  name = "document",
  children = [ #(DTD:0x24ab210 { name = "html" })]
  })
[3] (pry) main: 0> Nokogiri::HTML('').to_html
=> "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"http://www.w3.org/TR/REC-html40/loose.dtd\">\n\n"

而且,在这一点上,当您查看nokogiri::html文档的类时,您将得到一个nokogiri::html文档:
[4] (pry) main: 0> Nokogiri::HTML('').class
=> Nokogiri::HTML::Document

所以在puts page.class中检查类名对您没有任何好处而且,查找单元格将返回空:
[3] (pry) main: 0> Nokogiri::HTML('').css('td i.blue')
=> []

就个人而言,如果您想知道是否阅读了文档,请查看是否有任何字符:
abort("Got nothing") if page.empty?

而不是打印内容或查看document.class。
另外,我会使用page = File.read('file.html')而不是File.open,但那只是我。
这都指向找不到文件或文件为空您可以使用类似于cc的东西来查找它的存在,并在继续之前检查是否有内容。

10-07 19:07
查看更多