现在,我将HTML文档分成这样的小块:(正则表达式简化-跳过头标记内容和结束标记)
document.at('body').inner_html.split(/<\s*h[2-6][^>]*>/i).collect do |fragment|
Nokogiri::HTML(fragment)
end有没有更简单的方法来执行这种拆分?
文档非常简单,只包含标题、段落和格式化文本。例如:
<body>
<h1>Main</h1>
<h2>Sub 1</h2>
<p>Text</p>
-----
<h2>Sub 2</h2>
<p>Text</p>
-----
<h3>Sub 2.1</h3>
<p>Text</p>
-----
<h3>Sub 2.2</h3>
<p>Text</p>
</body>对于那个样本,我需要得到四个部分。
发布于 2011-11-08 04:51:01
我只是不得不做一些类似的事情。我将一个很大的超文本标记语言文件拆分为“章节”,其中一章以<h1>标记开始。
我还希望在散列中保留章节的标题,并忽略第一个<h1>标记之前的所有内容。
代码如下:
full_book = Nokogiri::HTML(File.read('full-book.html'))
@chapters = full_book.xpath('//body').children.inject([]) do |chapters_hash, child|
if child.name == 'h1'
title = child.inner_text
chapters_hash << { :title => title, :contents => ''}
end
next chapters_hash if chapters_hash.empty?
chapters_hash.last[:contents] << child.to_xhtml
chapters_hash
endhttps://stackoverflow.com/questions/3484874
复制相似问题