Как я могу получить исходный код изображения, заголовок и описание из этого html с помощью cheerio?

Я пытаюсь извлечь некоторый контент с веб-сайта, используя nodejs с cheerio. Я хочу извлечь следующее содержимое:

  1. Текст «Это мой пример текста заголовка».
  2. «Здесь будет текст моего описания».
  3. Источник изображения.

Вот html:

     <body>
     <div class="detail_loop">
         <img class="imfast" data-original="http://www.example.com/wp-content/uploads/2017/03/imageurl-250x150.jpg" title=""
              align="left" width="250" height="150"
              src="http://www.example.com/wp-content/uploads/2017/03/imageurl-250x150.jpg" style="display: block;">
         <h2>
             <a href="http://www.example.com/2017/04/576487/" rel="bookmark">This is my titile text</a>
         </h2>
         Here will be my description content.
         <div class="clear"></div>
         <div class="send_loop" style="display: none;">
             <a href="http://www.example.com/2017/04/576487//#respond" target="_blank">
                 <div class="send_com">
                     <div class="send_bubb">
                         <div class="count">
                             0
                         </div>
                     </div>
                 </div>
             </a>
             <a href="https://www.facebook.com/sendr.php?u=http://www.example.com/2017/04/576487/" target="_blank">
                 <div class="send_fb">
                     <div class="send_bubb">
                         <div class="count">
                             send
                         </div>
                     </div>
                 </div>
             </a>
             <a href="https://twitter.com/send?url=http://www.example.com/2017/04/576487/&amp;text=this is sample title;hashtags=example"
                target="_blank">
                 <div class="send_tt">
                     <div class="send_bubb">
                         <div class="count">
                             Tweet
                         </div>
                     </div>
                 </div>
             </a>
             <div class="clear"></div>
         </div>
         <div class="clear"></div>
         <div class="detail_loop_dvd"></div>
         <div class="clear"></div>
     </div>
    </body>

person Rahul Subedi    schedule 27.04.2017    source источник


Ответы (1)


Что-то вроде этого, к чему вы стремились? Можно, конечно, просто передать данные а-ля: cheerio.load('<html><body>…</html>')

Пример кода

Примечание. .text() вернет все дочерние элементы (другие ‹div› и т. д.), поэтому фильтр возвращает true только для текстовых узлов. –[#20832910]

const cheerio = require('cheerio');
const fs = require('fs');

/**
 * Given data saved in file 'index.html' in current path
 */
fs.readFile('index.html', {encoding: 'utf-8'}, (err, data) => {
    if (err) { console.log(err); return; }
    const $ = cheerio.load(data);

    /**
     * Print what you desire
     */
    console.log($('h2 a').text()); // Title text

    console.log($('div.detail_loop').contents().filter( function() {
            return this.type === 'text';
    }).text()); // Description content (without child nodes--only text)

    console.log($('img').attr('src')); // Image source
});
person Andrew Siplas    schedule 27.04.2017
comment
строковый метод .replace(/(^\s+|\s+$)/g, '') может быть полезен для обрезки всех пробелов до/после (от начала строки до первого непробельного символа…) строки, метод которой вы выполняете. - person Andrew Siplas; 27.04.2017