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.
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.
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
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