tags:

views:

476

answers:

4

what would be the most efficient way of grabbing all texts between html tags ?

<div>
<a> hi </a>
....

bunch of texts surrounded by html tags.

A: 
doc = Nokogiri::HTML(your_html)
doc.xpath("//text()").to_s
khelll
+1  A: 

Use a Sax parser. Much faster than the XPath option.

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
Bob Aman
+1  A: 

Here's how to get all the text in the question div of this page:

require 'rubygems'
require 'nokogiri'
require 'open-uri'

doc = Nokogiri::HTML(open("http://stackoverflow.com/questions/1512850/grabbing-text-between-all-tags-in-nokogiri"))
puts doc.css("#question").to_s
pjb3
A: 

inner_text?????

Anonymous Coward