使用cheerio,无法使用.attr获取属性

问题描述 投票:0回答:2

为什么我必须使用 link.attribs.href 而不是标准的 .attr('href') 方法?

...
res.on('end', () => {
     const $ = cheerio.load(content);
     const link = $('.more-link').get(0);
     // const url = link.attr('href');   <--- link.attr is not a function
     const url = link.attribs.href;       <--- works
     console.log(url);
});
node.js cheerio
2个回答
3
投票

根据 cheerio 文档

get(i)
从您正在使用的 Cheerio 实例中检索“DOM”元素。 Cheerio 实例对象有一个
.attr()
方法,但 DOM 元素只是存储该对象数据。

您可以使用

.first()
代替
.get(0)


0
投票

如果您尝试获取属性,请避免使用

.get()
。直接在 Cheerio 元素上调用
.attr("href")
,如下所示。

import cheerio from "cheerio"; // ^1.0.0-rc.12

const p = console.log;
const html = `<a class="more-link" href="hi"></a>`;
const $ = cheerio.load(html);

// these are possible but unnecessarily verbose...
const link = $(".more-link").get(0);
p($(link).attr("href")); // => hi
p(link.attribs.href); // => hi

// easiest to avoid .get() and just use:
p($(".more-link").attr("href")); // => hi
© www.soinside.com 2019 - 2024. All rights reserved.