【发布时间】:2021-04-04 15:54:52
【问题描述】:
我有一个 HTML 文档,看起来或多或少像这样:
<h1><a id="first-id"></a>First header</h1>
<h2>Foo</h2>
<p>Some text</p>
<h3>Bar 1</h3>
<p>Some text</p>
<h3>Bar 2</h3>
<p>Some text</p>
<h3>Bar 3</h3>
<p>Some text</p>
<h2>Baz</h2>
<p>Some text</p>
<h3>Bar 4</h3>
<p>Some text</p>
<h3>Bar 5</h3>
<p>Some text</p>
<h1>Second header</h1>
所有标题中还可以有一个或多个锚标记(如第一个标题)。
我的目标是:
- 通过
h1标签分割文档 - 能够分别处理
Bar \d之间的内容
即我想分别得到以下部分:
<h1><a id="first-id"></a>First header</h1>
<h2>Foo</h2>
<p>Some text</p>
<h3>Bar 1</h3>
<p>Some text</p>
<h3>Bar 2</h3>
<p>Some text</p>
<h3>Bar 3</h3>
<p>Some text</p>
<h2>Baz</h2>
<p>Some text</p>
<h3>Bar 4</h3>
<p>Some text</p>
<h3>Bar 5</h3>
<p>Some text</p>
<h1>Second header</h1>
直到现在,我都在使用 cheerio,但我无法找到一种方法将 HTML 很好地分割成不同的部分。
我怎样才能实现我的目标?有没有更适合我需求的图书馆?我想避免纯字符串操作,因为它很可能会弄乱所有锚标签...
【问题讨论】: