删除 <head> 个问题,我需要 guide/assistance
Removing <head> issues, I need guide/assistance
伙计们,我正在做一个网络解析器,它很好,但我看到 <head>
中的一些词把一切都搞砸了(body 中的 <strong>
也是如此) .我的代码是 This one here before nokogiri,但我是 ruby 编程新手,几个小时前才开始了解 Nokogiri。
我希望有人能帮助我完成这项工作。我需要阅读 URL,删除 <head>
和其中的所有内容,然后扫描页面其余部分的文字
PS:是否可以只带 body 来阅读?会更容易
PSS:关于<strong>
个标签,很难去掉吗?
我的练习是计算页面中有多少个特定单词,而不是源代码,这就是为什么我只需要抓取 body 并删除一个标签
真的希望有人能帮助我>.<
谢谢大家!
这里是我的实际失败代码/纯原创是here
require 'open-uri'
require 'cgi'
require 'nokogiri'
class Counter
def initialize(url)
@url = url
end
def decapitate
Nokogiri::HTML(url)
url.css('head').remove.to_s
end
def scan(word)
url.scan(word)
end
end
url, word = ARGV
puts "Found #{Counter.new(url).open.decapitate.scan(word).length} maches."
那里有很多错误。
url
in decapitate
是未定义的局部变量。您需要使用 @url
.
Nokogiri::HTML
需要 IO
对象或字符串,而不是 URL。您可能想使用 open(@url)
来阅读 URL 内容(我假设,因为您需要 open-uri
Nokogiri::HTML
return 是一个文档,但您没有将此 return 值存储在任何地方
因此,url
(或者 @url
)将是一个字符串,而字符串没有 css
方法;您想要将 css
应用于文档而不是
remove
将return被移除的节点;作为方法中的最后一件事,那将是 returned 的内容。因此 decapitate
将 return head
节点的文本。
最后,...decapitate.scan
会调用String#scan
方法,而不是你定义的方法。
你可以按如下方式做你想做的事:
def count(pattern, url)
doc = Nokogiri::HTML(open(url))
doc.css('head').remove
doc.text.scan(pattern).size
end
伙计们,我正在做一个网络解析器,它很好,但我看到 <head>
中的一些词把一切都搞砸了(body 中的 <strong>
也是如此) .我的代码是 This one here before nokogiri,但我是 ruby 编程新手,几个小时前才开始了解 Nokogiri。
我希望有人能帮助我完成这项工作。我需要阅读 URL,删除 <head>
和其中的所有内容,然后扫描页面其余部分的文字
PS:是否可以只带 body 来阅读?会更容易
PSS:关于<strong>
个标签,很难去掉吗?
我的练习是计算页面中有多少个特定单词,而不是源代码,这就是为什么我只需要抓取 body 并删除一个标签
真的希望有人能帮助我>.< 谢谢大家!
这里是我的实际失败代码/纯原创是here
require 'open-uri'
require 'cgi'
require 'nokogiri'
class Counter
def initialize(url)
@url = url
end
def decapitate
Nokogiri::HTML(url)
url.css('head').remove.to_s
end
def scan(word)
url.scan(word)
end
end
url, word = ARGV
puts "Found #{Counter.new(url).open.decapitate.scan(word).length} maches."
那里有很多错误。
url
indecapitate
是未定义的局部变量。您需要使用@url
.Nokogiri::HTML
需要IO
对象或字符串,而不是 URL。您可能想使用open(@url)
来阅读 URL 内容(我假设,因为您需要open-uri
Nokogiri::HTML
return 是一个文档,但您没有将此 return 值存储在任何地方因此,
url
(或者@url
)将是一个字符串,而字符串没有css
方法;您想要将css
应用于文档而不是remove
将return被移除的节点;作为方法中的最后一件事,那将是 returned 的内容。因此decapitate
将 returnhead
节点的文本。最后,
...decapitate.scan
会调用String#scan
方法,而不是你定义的方法。
你可以按如下方式做你想做的事:
def count(pattern, url)
doc = Nokogiri::HTML(open(url))
doc.css('head').remove
doc.text.scan(pattern).size
end