【问题标题】:Nokogiri text node contentsNokogiri 文本节点内容
【发布时间】:2012-08-16 17:33:06
【问题描述】:

有没有什么干净的方法可以用 Nokogiri 获取文本节点的内容?我现在正在使用

some_node.at_xpath( "//whatever" ).first.content

这对于获取文本来说似乎真的很冗长。

【问题讨论】:

    标签: ruby nokogiri


    【解决方案1】:

    你想要文本?

    doc.search('//text()').map(&:text)
    

    也许您不想要所有的空白和噪音。如果您只想要包含单词字符的文本节点,

    doc.search('//text()').map(&:text).delete_if{|x| x !~ /\w/}
    

    编辑:看来您只想要单个节点的文本内容:

    some_node.at_xpath( "//whatever" ).text
    

    【讨论】:

    • 只是一个后续:如果你想查找所有非空白文本节点并且你正在使用 Rails,那么你有 present?blank? 方法。其中每一个都是等效的:doc.search('//text()').map(&:text).delete_if &:blank?doc.search('//text()').map(&:text).keep_if &:present?
    • 或者,更简单地说,some_node.at('whatever').text
    【解决方案2】:

    只需寻找文本节点:

    require 'nokogiri'
    
    doc = Nokogiri::HTML(<<EOT)
    <html>
    <body>
    <p>This is a text node </p>
    <p> This is another text node</p>
    </body>
    </html>
    EOT
    
    doc.search('//text()').each do |t|
      t.replace(t.content.strip)
    end
    
    puts doc.to_html
    

    哪些输出:

    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
    <html><body>
    <p>This is a text node</p>
    <p>This is another text node</p>
    </body></html>
    

    顺便说一句,您的代码示例不起作用。 at_xpath( "//whatever" ).first 是多余的,会失败。 at_xpath 只会找到第一个匹配项,返回一个节点。 first 在这一点上是多余的,如果它可以工作的话,但它不会因为 Node 没有 first 方法。


    我有&lt;data&gt;&lt;foo&gt;bar&lt;/foo&gt;&lt;/bar&gt;,我如何在不执行doc.xpath_at( "//data/foo" ).children.first.content 的情况下获得“栏”文本?

    假设 doc 包含解析后的 DOM:

    doc.to_xml # => "<?xml version=\"1.0\"?>\n<data>\n  <foo>bar</foo>\n</data>\n"
    

    获取第一个匹配项:

    doc.at('foo').text       # => "bar"
    doc.at('//foo').text     # => "bar"
    doc.at('/data/foo').text # => "bar"
    

    获取所有出现并取第一个:

    doc.search('foo').first.text      # => "bar"
    doc.search('//foo').first.text    # => "bar"
    doc.search('data foo').first.text # => "bar"
    

    【讨论】:

    • 呃,对不起,我的意思是 children.first.content。不过,您的示例并不是我想要的——假设我有 bar,我如何在不执行 doc.xpath_at("//数据/foo").children.first.content?
    • 明确自己想要什么真的很重要。否则我们无法为您提供帮助。查看添加的内容。
    • 我以为我是 - 我以为 xpath_at 很清楚我知道我正在寻找的节点并且只是以一种愚蠢的方式获取它们的内容。
    猜你喜欢
    • 1970-01-01
    • 2014-06-06
    • 2015-10-17
    • 1970-01-01
    • 1970-01-01
    • 2020-05-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多