直接在Nokogiri的标签内获取文本
我有一些HTML看起来像:
Hello (2009)
我已将所有HTML加载到名为record
的变量中。 我需要解析一年,即2009年是否存在。
如何获取dt
标签内的文本而不是标签内的文本? 我使用了record.search("dt").inner_text
,这给了我一切。
这是一个微不足道的问题,但我还没有想到这一点。
要获得所有带有文本的直接子项,而不是任何其他子子项,您可以像这样使用XPath:
doc.xpath('//dt/text()')
或者如果您想使用搜索:
doc.search('dt').xpath('text()')
使用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('hi BOO there ').root puts root.text #=> hi BOO there puts own_text(root) #=> hi there
dt
元素有两个子元素,因此您可以通过以下方式访问它:
doc.search("dt").children.last.text