在html标签之间抓取所有文本的最有效方法是什么?
<div>
<a> hi </a>
....
Run Code Online (Sandbox Code Playgroud)
一堆文字被html标签包围.
khe*_*lll 25
doc = Nokogiri::HTML(your_html)
doc.xpath("//text()").to_s
Run Code Online (Sandbox Code Playgroud)
使用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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9747 次 |
| 最近记录: |