【发布时间】:2016-07-19 05:47:00
【问题描述】:
使用 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 做到这一点?
【问题讨论】: