2009-10-03 43 views

回答

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

谢谢!工作正常+1 – rusllonrails 2017-11-25 13:42:43

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 
+0

这怎么可能被改变为仅在body标签之间获取文本? – Omnipresent 2010-12-11 16:27:53

+0

设置一个标志,并且只有在身体标签关闭后才能看到身体标签开始和停止捕捉后才开始捕捉角色。 – 2010-12-13 00:35:11

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 
2

只要做到:

doc = Nokogiri::HTML(your_html) 
doc.xpath("//text()").text 
相关问题