如何使用Nokogiri从Ruby中的HTML文档中获取所有节点

问题描述 投票:4回答:1

我正在尝试使用Nokogiri从HTML文档中获取所有节点。

我有这个HTML:

<html>
<body>
  <h1>Header1</h1>
  <h2>Header22</h2>
  <ul>
    <li>Li1</li>
    <ul>
       <li>Li1</li>
       <li>Li2</li>
    </ul>
  </ul>
</body>
</html>

字符串版本:

string_page = "<html><body><h1>Header1</h1><h2>Header22</h2><ul><li>Li1</li><ul><li>Li1</li><li>Li2</li></ul></ul></body></html>"

我创建了一个对象:

page = Nokogiri.HTML(string_page)

而且我试图遍历它:

result = []
page.traverse { |node| result << node.name unless node.name == "text" }
=> ["html", "h1", "h2", "li", "li", "li", "ul", "ul", "body", "html", "document"]

但是我不喜欢元素的顺序。我需要一个与它们出现顺序相同的数组:

["html", "body", "h1", "h2", "ul", "li", "ul", "li", "li" ]

我不需要结束标记。

有人有更好的解决方案来完成此任务吗?

ruby nokogiri
1个回答
3
投票

如果要按顺序查看节点,请使用XPath选择器,例如'*',表示“一切”,从根节点开始:

require 'nokogiri'
string_page = "<html><body><h1>Header1</h1></body></html>"
doc = Nokogiri::HTML(string_page)
doc.search('*').map(&:name)
# => ["html", "body", "h1"]

但是,我们通常不在乎遍历每个节点,我们通常也不想这样做。我们想要找到某种类型的所有节点,或者单个节点,因此我们在标记中查找地标,然后从那里开始:

doc.at('h1').text # => "Header1"

或:

html = "<html><body><table><tr><td>cell1</td></tr><tr><td>cell2</td></tr></h1></body></html>"
doc = Nokogiri::HTML(html)
doc.search('table tr td').map(&:text) # => ["cell1", "cell2"]

或:

doc.search('tr td').map(&:text) # => ["cell1", "cell2"]

或:

doc.search('td').map(&:text) # => ["cell1", "cell2"]

注意:没有理由使用更长的示例HTML字符串;它只是使问题杂乱无章,因此请使用一个最小的示例。

另请参见“ How to avoid joining all text from Nodes when scraping”。

© www.soinside.com 2019 - 2024. All rights reserved.