【问题标题】:Why is the following Nokogiri/XPath code removing tags inside the node?为什么以下 Nokogiri/XPath 代码会删除节点内的标签?
【发布时间】:2015-04-12 05:17:19
【问题描述】:

进入的文档结构如下:

<span class="footnote">Hello there, <a href="http:google.com">link</a></span>

XPath 搜索是:

@doc = set_nokogiri(html)

footnotes = @doc.xpath(".//span[@class = 'footnote']")
footnotes.each_with_index do |footnote, index|
    puts footnote
end

上面的脚注变成:

<span>Hello there, link</span>

我认为我的 XPath 是错误的,但我很难找出原因。

我在输出中有错误的标签,应该更加小心。关键是 &lt;a&gt; 标记已被剥离,但其内容仍包含在内。

我还添加了set_nokogiri 行以防万一。

【问题讨论】:

  • 这段代码肯定不会返回p 元素。请发布一个示例输入和代码,以便重现您显示的输出:stackoverflow.com/help/mcve
  • 我无法重现这一点,得到以下结果:&lt;span class="footnote"&gt;Hello there, &lt;a href="http:google.com"&gt;link&lt;/a&gt;&lt;/span&gt;.

标签: ruby xpath nokogiri jekyll


【解决方案1】:

我无法复制问题:

require 'nokogiri'

doc = Nokogiri::HTML(<<EOT)
<span class="footnote">Hello there, <a href="http:google.com">link</a></span>
EOT

footnotes = doc.xpath(".//span[@class = 'footnote']")
footnotes.to_xml # => "<span class=\"footnote\">Hello there, <a href=\"http:google.com\">link</a></span>"
footnotes.each do |f|
  puts f
end
# >> <span class="footnote">Hello there, <a href="http:google.com">link</a></span>

另一个问题是&lt;a&gt; 标记具有无效的href URL。

<a href="http:google.com">link</a>

应该是:

<a href="http://google.com">link</a>

【讨论】:

  • 不,像 .//element 这样的 XPath 表达式并不意味着搜索文档中的任何位置 - 它意味着只搜索 当前上下文节点descendant-or-self:: 轴 - 这会发生在这种情况下成为文档节点。顺便说一句,在这种情况下,.//element//element 的含义相同。那么//span[@class = 'footnote']./span[@class = 'footnote'] 不一样。前者选择文档中任意位置的span 元素,后者仅在它们是当前上下文节点的直接子节点时才选择它们。
  • 不客气-但我的评论有点太消极了。 //span[@class = 'footnote'] 确实比 .//span[@class = 'footnote'] 更清晰 - 为此 +1。您是否同意在给定输入 HTML 和代码的情况下不可能得出 OP 描述的结果?
  • 我没有得到 OP 声称的相同结果。这是写得很糟糕的 Nokogiri 代码,但没有什么可以去掉 &lt;a&gt; 标签,我也没有看到问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-09
  • 2019-09-12
相关资源
最近更新 更多