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

1

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

Теги:
cheerio

1 ответ

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();

Ещё вопросы

Сообщество Overcoder
Наверх
Меню