【问题标题】:Remove all tags before and after a given id - Cheerio删除给定 ID 前后的所有标签 - Cheerio
【发布时间】:2020-07-07 06:25:47
【问题描述】:

我正在使用cheerio编辑html,我从爬取的网站获得。

我正在尝试删除给定 id 之前和给定 id 之后的所有标签,例如,如果我的 html 是:

<div>
 <h2> This is it! </h2>
 <div>
   <h1> More helpful <h1>
 <div>
 <p> Hello, world </p>
 <h2 id='intro'> About the webpage <h2>
 <h2> This is it! </h2>
 <div>
   <h1> More helpful <h1>
 <div>
 <p> Hello, world </p>
 <p id="footer">footer</p>
 <h2> This is it! </h2>
 <div>
   <h1> More helpful <h1>
 <div>
 <p> Hello, world </p>
</div>

我想删除 id 'intro' 之前的所有标签和 id 'footer' 之后的所有标签,以便生成

<div>
 <h2 id='intro'> About the webpage <h2>
 <h2> This is it! </h2>
 <div>
   <h1> More helpful <h1>
 <div>
 <p> Hello, world </p>
 <p id="footer">footer</p>
</div>

如何使用cheerio 或任何其他库来做到这一点?我正在关注https://cheerio.js.org/,我找不到在给定标签之前或之后选择所有对等标签的方法。是否可以使用其他库?

【问题讨论】:

    标签: html web-crawler cheerio


    【解决方案1】:

    我找到了解决办法:

    cheerio('#intro', html).prevAll().remove();
    cheerio('#footer', html).nextAll().remove();
    

    【讨论】:

      猜你喜欢
      • 2015-09-17
      • 1970-01-01
      • 2019-04-21
      • 2020-01-15
      • 2013-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-27
      相关资源
      最近更新 更多