Search code examples
javascriptjquerynode.jscheerio

Get the last div element using cheerio


Hello I am implementing a scraper which scrape the latest message received in a telegram public channel. This is how the html is enter image description here

I can fetch all the divs under section class tgme_channel_history. It has five divs under it which means five different messages. I want to get only the last div. How can I do that. You can check the live HTML here https://telegram.me/s/newlink01/

const $ = require('cheerio');

const url = 'https://telegram.me/s/newlink01/';

 rp(url)
        .then(function (html) {
            //success!
            const wikiUrls = [];

            $('.tgme_channel_history', html).each(function () {

                wikiUrls.push($(this).text()


            });
            console.log(wikiUrls[0]);

  })
        .catch(function (err) {
            //handle error
        });

Solution

  • You can pass a selector to jQuery.children() to select all child div elements, and then call jQuery.last() to fetch the final one in the set.

    $(".tgme_channel_history").children("div").last();