现在,我正在将HTML文档拆分成这样的小块:(正则表达式简化 - 跳过标题标记内容和结束标记)
document.at('body').inner_html.split(/<\s*h[2-6][^>]*>/i).collect do |fragment|
Nokogiri::HTML(fragment)
end
Run Code Online (Sandbox Code Playgroud)
有没有更简单的方法来执行拆分?
该文档非常简单,只包含标题,段落和格式化文本.例如:
<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>
Run Code Online (Sandbox Code Playgroud)
对于那个样本,我需要得到四个.
我只需要做类似的事情.我将一个大的HTML文件拆分为"章节",其中章节由<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
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1571 次 |
| 最近记录: |