gpt4 book ai didi

ruby 没有从终端正确执行

转载 作者:太空宇宙 更新时间:2023-11-03 16:55:15 26 4
gpt4 key购买 nike

我有以下 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' 从终端调用它。但是,我试图让脚本在某个时间点运行,并尝试使用 Keyboard Maestro 或 Platypus 调用脚本,但尽管它运行但似乎没有完成该行

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 文档:

[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,但那只是我。

这都指向文件未找到或为空。您可以使用 File.exists?('file.html') 之类的东西来查找它的存在,并使用 File.size('file.html') 来检查它是否存在如果在继续之前它有内容。

关于ruby 没有从终端正确执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11783070/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com