Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/image-processing/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 在Nokogiri的所有标签之间抓取文本?_Ruby_Nokogiri - Fatal编程技术网

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

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>

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

如何将此更改为仅获取正文标记之间的文本?设置一个标志,仅在看到正文标记后开始捕获字符,并在正文标记关闭后停止捕获。也请签出