在Nokogiri的所有标签之间抓取文字?

KJW*_*KJW 9 ruby nokogiri

在html标签之间抓取所有文本的最有效方法是什么?

<div>
<a> hi </a>
....
Run Code Online (Sandbox Code Playgroud)

一堆文字被html标签包围.

khe*_*lll 25

doc = Nokogiri::HTML(your_html)
doc.xpath("//text()").to_s
Run Code Online (Sandbox Code Playgroud)


Bob*_*man 5

使用Sax解析器.比XPath选项快得多.

require "nokogiri"

some_html = <<-HTML
<html>
  <head>
    <title>Title!</title>
  </head>
  <body>
    This is the body!
  </body>
</html>
HTML

class TextHandler < Nokogiri::XML::SAX::Document
  def initialize
    @chunks = []
  end

  attr_reader :chunks

  def cdata_block(string)
    characters(string)
  end

  def characters(string)
    @chunks << string.strip if string.strip != ""
  end
end
th = TextHandler.new
parser = Nokogiri::HTML::SAX::Parser.new(th)
parser.parse(some_html)
puts th.chunks.inspect
Run Code Online (Sandbox Code Playgroud)