Ruby 在Nokogiri的所有标签之间抓取文本?
在html标记之间获取所有文本的最有效方法是什么Ruby 在Nokogiri的所有标签之间抓取文本?,ruby,nokogiri,Ruby,Nokogiri,在html标记之间获取所有文本的最有效方法是什么 <div> <a> hi </a> .... 你好 .... 由html标记包围的一堆文本。使用Sax解析器。比XPath选项快得多 doc = Nokogiri::HTML(your_html) doc.xpath("//text()").to_s require "nokogiri" some_html = <<-HTML <html> <head>
<div>
<a> hi </a>
....
你好
....
由html标记包围的一堆文本。使用Sax解析器。比XPath选项快得多
doc = Nokogiri::HTML(your_html)
doc.xpath("//text()").to_s
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
需要“nokogiri”
some_html=以下是如何获取此页面问题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
只要做:
doc = Nokogiri::HTML(your_html)
doc.xpath("//text()").text
如何将此更改为仅获取正文标记之间的文本?设置一个标志,仅在看到正文标记后开始捕获字符,并在正文标记关闭后停止捕获。也请签出