如何在不使用 Nokogiri 抓取 ul 的嵌套标签的情况下捕获 p 和 ul 标签?

How to capture p and ul tags without grabbing ul's nested tags with Nokogiri?

使用Nokogiri,我正在尝试获取所有"first"级别pulHTML标签,但有点困难。

例如,这是我正在使用的HTML

<p><strong>Just testing <em>something</em> out&nbsp;</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 标签之一。因此,我的代码最终会对该文本执行两次相同的操作。

所以我正在寻找的是 "exclude" 嵌套标签,如果它与父标签相同,那么当我 运行 html.xpath("//p | //u") 或类似的东西时,它会查看ul 标记并将其全部视为 xpath 输出数组中的一个元素

有没有办法用 Nokogiri 做到这一点?

您可以使用以下模式 select 使用 XPath 的特定名称的第一级元素:

//target_element[not(ancestor::target_element)]

因此对于您的特定情况,XPath 如下:

//p[not(ancestor::p)] | //ul[not(ancestor::ul)]