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

时间:2009-10-03 05:04:01

标签: ruby nokogiri

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

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

由html标签包围的一堆文本。

4 个答案:

答案 0 :(得分:25)

doc = Nokogiri::HTML(your_html)
doc.xpath("//text()").to_s

答案 1 :(得分: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

答案 2 :(得分:2)

只是做:

doc = Nokogiri::HTML(your_html)
doc.xpath("//text()").text

答案 3 :(得分:1)

以下是如何获取此页面的问题div中的所有文本:

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