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

标签 html ruby xpath nokogiri

使用 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 做到这一点?

最佳答案

您可以使用以下模式通过 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/

相关文章:

javascript - 将 OpenLayers 添加到 rails 项目

ruby-on-rails - 有条件地生成回形针附件的样式

Python selenium xpath 获取文本为空

javascript - 根据选定的下拉列表值创建动态复选框

javascript - React - 单击更改 CSS 属性(箭头功能)

javascript - 如何从 Adob​​e Business Catalyst 中的同一登录页面创建单独的安全区域?

python - RubyPython 导入错误 : No module named site

python - 使用 xpath 和 LXML 或 selenium 从 HTML 表中抓取数据

xml - 使用命名空间的 Xpath 测试

html - 显示 :none change the width