【问题标题】:Get text directly inside a tag in Nokogiri直接在 Nokogiri 中的标签内获取文本
【发布时间】:2012-06-03 16:13:21
【问题描述】:

我有一些看起来像这样的 HTML:

<dt>
  <a href="#">Hello</a>
  (2009)
</dt>

我已经将所有 HTML 加载到一个名为 record 的变量中。如果存在,我需要解析出年份,即 2009 年。

如何获取dt 标签内的文本,而不是a 标签内的文本?我用过record.search("dt").inner_text,这给了我一切。

这是一个微不足道的问题,但我还没有设法弄清楚。

【问题讨论】:

  • 还要注意,实际上dt 内部有两个文本节点(除非您使用noblanks 选项解析HTML):第一个文本节点是"\n ",在&lt;a&gt; 之前,第二个文本节点是"\n (2009)\n"

标签: ruby nokogiri


【解决方案1】:

dt 元素有两个子元素,因此您可以通过以下方式访问它:

doc.search("dt").children.last.text

【讨论】:

    【解决方案2】:

    要获取所有带有文本的直接子级,而不是任何其他子级,您可以像这样使用 XPath:

    doc.xpath('//dt/text()')
    

    或者如果你想使用搜索:

    doc.search('dt').xpath('text()')
    

    【讨论】:

    • 上面的方法给你一个XML::Text节点的NodeSet;您可能想使用at_xpath(或只是at)来获取单个结果,然后在该节点上调用.content.text 方法以从中获取文本作为字符串。
    【解决方案3】:

    使用 XPath 准确选择您想要的内容(正如 @Casper 所建议的那样)是正确的答案。

    def own_text(node)
      # Find the content of all child text nodes and join them together
      node.xpath('text()').text
    end
    

    这是另一个有趣的答案:)

    def own_text(node)
      node.clone(1).tap{ |copy| copy.element_children.remove }.text
    end
    

    实际操作:

    require 'nokogiri'
    root = Nokogiri.XML('<r>hi <a>BOO</a> there</r>').root
    puts root.text       #=> hi BOO there
    puts own_text(root)  #=> hi  there
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-01
      • 2016-09-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多