我有一些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)
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)
该dt元素有两个子元素,因此您可以通过以下方式访问它:
doc.search("dt").children.last.text
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15331 次 |
| 最近记录: |