如何使用 Nokogiri 拆分 HTML 文档? [英] How to split a HTML document using Nokogiri?

查看:30
本文介绍了如何使用 Nokogiri 拆分 HTML 文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在,我正在将 HTML 文档拆分成这样的小块:(正则表达式简化-跳过标题标签内容和结束标签)

Right now, I'm splitting the HTML document to small pieces like this: (regular expression simplified - skipping header tag content and closing tag)

document.at('body').inner_html.split(/<\s*h[2-6][^>]*>/i).collect do |fragment|
  Nokogiri::HTML(fragment)
end

有没有更简单的方法来执行这种拆分?

Is there an easier way to perform that splitting?

文档很简单,里面只有标题、段落和格式化的文本.例如:

The document is very simple, just headers, paragraphs and formatted text in it. For example:

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

对于那个样品,我需要四件.

For that sample, I need to get four pieces.

推荐答案

我只是做了一些类似的事情.我将一个大的 HTML 文件分成章节",其中一章由 <h1> 标签开始.

I just had to do something similar. I split a large HTML file in to "chapters" where a chapter is started by an <h1> tag.

我还想在哈希中保留章节的标题,并忽略第一个

标签之前的所有内容.

I also wanted to keep the title of the chapters in the hash and ignore everything before the first <h1> tag.

代码如下:

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

这篇关于如何使用 Nokogiri 拆分 HTML 文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆