【问题标题】:Slice HTML according to headers根据标题对 HTML 进行切片
【发布时间】: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 很好地分割成不同的部分。

我怎样才能实现我的目标?有没有更适合我需求的图书馆?我想避免纯字符串操作,因为它很可能会弄乱所有锚标签...

【问题讨论】:

    标签: html node.js cheerio


    【解决方案1】:

    你想用 nextUntil 进行迭代:

    $('h1').each((i, h1) => {
      console.log('-' + $.html($(h1)))
      let $2 = cheerio.load($.html($(h1).nextUntil('h1')))
      $2('h2,h3').each((i, h2) => {
        console.log('--' + $.html($(h2)))
        console.log('---' + $.html($(h2).nextUntil('h2,h3')))
      })
    })
    

    【讨论】:

      【解决方案2】:

      将段的 html 代码放在带有 id 的 div 标记之间并按 id 定位 div 似乎是一个好习惯:

      <div id="firstHeader">
        <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>
      </div>
      
      <div id="secondHeader">
        <h1>Second header</h1>
      </div>

      然后使用 javascript 定位:

      const firstHeader = document.getElementById('firstHeader')
      const secondHeader = document.getElementById('secondHeader')

      不确定这是不是你的意思。

      【讨论】:

      • 遗憾的是不完全。我正在将一个 Word 文档解析为 HTML,它列出了我提到的结构。因此,我的标题周围没有divs。另外,ids 不是固定的,因为文档会经常更新。
      • 啊,对不起。希望你能尽快得到一个好的答案。祝您工作顺利,因为我无法帮助您解决问题。
      • 谢谢!抱歉我的问题不太清楚...
      猜你喜欢
      • 2021-04-02
      • 2017-05-21
      • 1970-01-01
      • 1970-01-01
      • 2015-04-15
      • 1970-01-01
      • 2020-12-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多