我有以下代码,旨在输出cheerio从特定html页面检索的所有标题名称。
const cheerio = require('cheerio');
const rp = require('request-promise');
async function run() {
const options = {
uri: '<SOME_URL>',
resolveWithFullResponse: true,
transform: (body) => {
return cheerio.load(body);
}
}
try{
const $ = await rp(options);
$("h1, h2, h3, h4, h5, h6").map(e => {
console.log(e);
});
}catch(e){
console.log(e);
}
}
run();
但是上述代码的输出类似于
0
1
2
...
我尝试将console.log(e)
更改为e.attr('name')
,然后返回错误
TypeError:e.attr不是函数
答案 0 :(得分:0)
您的问题是$().map
给您索引作为第一个参数,给元素作为第二个参数。
我想你需要这个:
const cheerio = require('cheerio');
const rp = require('request-promise');
const uri = 'http://www.somesite.com';
async function run() {
const options = {
uri,
resolveWithFullResponse: true,
transform: (body) => {
return cheerio.load(body);
}
}
try{
const $ = await rp(options);
$("h1, h2, h3, h4, h5, h6").map((_,element) => {
console.log($(element).html()) // just output the content too to check everything is alright
console.log(element.name);
});
}catch(e){
console.log(e);
}
}
run();