Как получить все названия заголовков, полученные cheerio?

У меня есть следующий код, который предназначен для вывода всех имен заголовков, полученных 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')то мне возвращается ошибка

Ошибка типа: e.attr не является функцией

1 ответ

Решение

Ваша проблема в том, что $().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();
Другие вопросы по тегам