伙计们,我正在做一个web解析器,它很好,但是我看到<head>
里面的一些单词把一切都搞砸了(身体里的<strong>
也搞砸了)。我的代码是This one here before nokogiri但我是ruby编程新手,几个小时前才开始了解nokogiri。
我希望有人能帮我把这件事做好。我需要。阅读url,删除<head>
和其中的所有内容,然后扫描页面其余部分的单词
附言:有没有可能只带上尸体读一读?会更容易
pss:关于<strong>
标签,是否很难移除?
我的练习是计算页面中有多少特别的单词,而不是源代码,这就是为什么我只需要抓住正文并删除标记
真的希望有人能帮助我>。<
伙计们!
这是我的实际故障代码/纯原件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
中的decapitate
是未定义的局部变量。您需要使用@url
。Nokogiri::HTML
需要IO
对象或字符串,而不是url。您可能想使用open(@url)
来读取url内容(假设您需要open-uri
Nokogiri::HTML
返回文档,但不在任何地方存储此返回值
因此,url
(或者更确切地说是@url
)将是一个字符串,并且字符串没有css
方法;您需要将css
应用于文档remove
将返回已移除的节点;作为方法中的最后一件事,这将是返回的内容。因此decapitate
将返回head
节点的文本。
最后,...decapitate.scan
将调用String#scan
方法,而不是您定义的方法。
你可以做你想做的事情如下:
def count(pattern, url)
doc = Nokogiri::HTML(open(url))
doc.css('head').remove
doc.text.scan(pattern).size
end