直接在Nokogiri的标签内获取文本

Mri*_*lla 18 ruby nokogiri

我有一些HTML看起来像:

<dt>
  <a href="#">Hello</a>
  (2009)
</dt>
Run Code Online (Sandbox Code Playgroud)

我已经将所有HTML加载到一个名为的变量中record.我需要解析一年,即2009年是否存在.

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

这是一个微不足道的问题,但我还没有想到这一点.

Cas*_*per 17

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

doc.xpath('//dt/text()')
Run Code Online (Sandbox Code Playgroud)

或者如果您想使用搜索:

doc.search('dt').xpath('text()')
Run Code Online (Sandbox Code Playgroud)

  • 上面的方法为您提供了一个[`XML :: Text`](http://nokogiri.org/Nokogiri/XML/Text.html)节点的NodeSet; 您可能希望使用`at_xpath`(或只是`at`)来获取单个结果,然后在该节点上调用`.content`或`.text`方法以将文本作为字符串从中获取. (3认同)

Phr*_*ogz 10

使用XPath来准确选择你想要的东西(正如@Casper建议的那样)是正确的答案.

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

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

def own_text(node)
  node.clone(1).tap{ |copy| copy.element_children.remove }.text
end
Run Code Online (Sandbox Code Playgroud)

看到行动:

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
Run Code Online (Sandbox Code Playgroud)


Cha*_*nap 5

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

doc.search("dt").children.last.text
Run Code Online (Sandbox Code Playgroud)