使用Nokogiri列出HTML中存在哪些标记

时间:2015-03-24 21:02:54

标签: ruby-on-rails ruby nokogiri

我正在尝试使用Nokogiri来计算HTML页面上的所有属性。假设我搜索Google,我怎样才能使用Nokogiri计算该域名来源的每个HTML标记?

这是我的出发点,即没有产生我期望的结果:

require 'open-uri'
doc = Nokogiri::HTML(open("http://www.stackoverflow.com/"))
@doc = Nokogiri::XML(doc)
@doc.xpath("//*")

1 个答案:

答案 0 :(得分:4)

这样的事情会做你正在寻找的事情:

require 'nokogiri'
require 'open-uri'
require 'awesome_print'

# Create a Nokogiri document
doc = Nokogiri::HTML(open("http://www.stackoverflow.com/").read)
# Iterate each node in the result set, and for each tag, increment the appropriate counter on the output hash
ap doc.xpath("//*").map(&:name).each_with_object({}) {|n, r| r[n] = (r[n] || 0) + 1 }

结果:

{
        "html" => 1,
        "head" => 1,
       "title" => 1,
        "link" => 5,
        "meta" => 7,
      "script" => 13,
        "body" => 1,
    "noscript" => 2,
         "div" => 1429,
          "h3" => 99,
           "a" => 717,
          "ul" => 5,
          "li" => 89,
        "span" => 490,
        "form" => 1,
       "input" => 1,
          "br" => 4,
           "b" => 3,
          "ol" => 8,
          "h1" => 1,
         "img" => 9,
          "h2" => 1,
          "h4" => 1,
       "table" => 1,
          "tr" => 2,
          "th" => 5,
          "td" => 7
}

#name是每个节点上具有标记名称的属性,因此我们只将节点集减少为关键字输出哈希值。