使用 cheerio,无法使用 .attr 获取属性
using cheerio, can't get attributes using .attr
为什么我必须使用 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);
});
根据 cheerio documentation,get(i)
从您正在使用的 cheerio 实例中检索 "DOM" 元素。 cheerio 实例对象有一个 .attr()
方法,但 DOM 元素只是它们存储该对象数据。
您可以使用 .first()
而不是 .get(0)
。
为什么我必须使用 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);
});
根据 cheerio documentation,get(i)
从您正在使用的 cheerio 实例中检索 "DOM" 元素。 cheerio 实例对象有一个 .attr()
方法,但 DOM 元素只是它们存储该对象数据。
您可以使用 .first()
而不是 .get(0)
。