Cheerio 如何忽略某个标签的元素

Dyl*_*ski 1 node.js cheerio

我正在抓取网页的正文:

axios.get(url)
.then(function(response){
        var $ = cheerio.load(response.data);
        var body = $('body').text();
    });
Run Code Online (Sandbox Code Playgroud)

问题是,我想从<footer>标签中排除内容。我怎么做?

jfr*_*d00 7

Cheerio 在解析 HTML 时创建一个伪 DOM。您可以像在浏览器中操作 DOM 一样操作该 DOM。在您的特定情况下,您可以使用任意数量的方法从 DOM 中删除项目,例如

 .remove()
 .replaceWith()
 .empty()
 .html()
Run Code Online (Sandbox Code Playgroud)

因此,基本思想是您将使用选择器来查找页脚元素,然后将其删除,如下所示:

$('footer').remove();
Run Code Online (Sandbox Code Playgroud)

然后,在删除这些元素后获取文本:

var body = $('body').text();
Run Code Online (Sandbox Code Playgroud)