【问题标题】:How to capture p and ul tags without grabbing ul's nested tags with Nokogiri?如何在不使用 Nokogiri 抓取 ul 的嵌套标签的情况下捕获 p 和 ul 标签?
【发布时间】:2016-07-19 05:47:00
【问题描述】:

使用 Nokogiri,我正在尝试获得所有“第一”级别的pul HTML 标签,但有点困难。

例如,这是我正在使用的 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 标签之一。因此,我的代码最终对这个文本做了两次同样的事情。

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

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

【问题讨论】:

    标签: html ruby xpath nokogiri


    【解决方案1】:

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

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

    因此,对于您的具体情况,XPath 如下:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-28
      • 2022-07-01
      • 2011-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-04
      相关资源
      最近更新 更多