简体   繁体   English

使用 Cheerio 获取最后一个 div 元素

[英]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这就是 html 的样子在此处输入图像描述

I can fetch all the divs under section class tgme_channel_history .我可以获取 class tgme_channel_history部分下的所有 div。 It has five divs under it which means five different messages.它下面有五个 div,这意味着五个不同的消息。 I want to get only the last div.我只想得到最后一个 div。 How can I do that.我怎样才能做到这一点。 You can check the live HTML here https://telegram.me/s/newlink01/您可以在此处查看实时 HTML 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
        });

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.您可以将选择器传递给jQuery.children()到 select 所有子div元素,然后调用jQuery.last()以获取集合中的最后一个。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM