使用 Nokogiri,我试图获取所有“第一”级 p
和 ul
HTML 标记,但遇到了一点困难。
例如,这是我正在使用的 HTML
<p><strong>Just testing <em>something</em> out </strong>over here.</p>
<p>Here's a paragraph that contains bullets though:</p>
<ul>
<li>One thing here.
<ul>
<li>One more thing</li>
</ul>
</li>
<li>Another thing here</li>
</ul>
<p>
<br>
</p>
<ul>
<li>nothing</li>
</ul>
<p>Some more text.</p>
我想抓取所有段落和所有无序列表。因为无序列表没有被 p
标签包围,所以我也必须使用以下示例来获取它们:
#data = the HTML above
html = Nokogiri::HTML(data)
html.xpath("//p | //ul").each do |p|
# some code
end
问题是 html.xpath("//p |//ul")
的输出看起来像这样:
<p><strong>Just testing <em>something</em> out </strong>over here.</p>
<p>Here's a paragraph that contains bullets though:</p>
<ul>
<li>One thing here.
<ul>
<li>One more thing</li>
</ul>
</li>
<li>Another thing here</li>
</ul>
<ul>
<li>One more thing</li>
</ul>
<p>
<br>
</p>
<ul>
<li>nothing</li>
</ul>
<p>Some more text.</p>
如您所见,One more thing
会自行重复,因为它是 ul
内嵌套的 ul
标记之一。因此,我的代码最终会对该文本执行相同的操作两次。
所以我正在寻找的是“排除”嵌套标签,如果它与父标签相同,这样当我运行 html.xpath("//p |//u")
或类似的东西,它查看 ul
标签并将其全部视为 xpath 输出数组中的一个元素
有没有办法用 Nokogiri 做到这一点?
最佳答案
您可以使用以下模式通过 XPath 选择具有特定名称的第一级元素:
//target_element[not(ancestor::target_element)]
因此对于您的具体情况,XPath 如下:
//p[not(ancestor::p)] | //ul[not(ancestor::ul)]
关于html - 如何在不使用 Nokogiri 抓取 ul 的嵌套标签的情况下捕获 p 和 ul 标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36322120/