【问题标题】:How can I scrape data from a chart using Cheerio?如何使用 Cheerio 从图表中抓取数据?
【发布时间】:2019-04-01 15:47:06
【问题描述】:

我正在尝试从聊天中抓取数据,但我不知道如何在 NodeJs 中使用 Cheerio 来做到这一点

我需要获取消息列表的所有昵称(msg-nickname):

到目前为止我有:

server.js

var express = require('express');
var fs = require('fs');
var request = require('request');
var cheerio = require('cheerio');
var app     = express();

app.get('/scrape', function(req, res){

url = 'https://www.nimo.tv/live/6865137196';

request(url, function(error, response, html){
    if(!error){
        var $ = cheerio.load(html);

    var nickname, msg;
    var json = { nickname : "", msg : ""};
    const messages = [];

    $('.msg-nickname',).each(function(i, elem){
        console.log(elem);
        messages[i] = elem.parent.children.text();
    })

    console.log($('#chat-room__list').children('msg-wrap').text)

    
}

app.listen('8081') 
console.log('Magic happens on port 8081'); 
exports = module.exports = app;

而且每次您在列表中有新项目时,我还需要更新以检查和更新列表。

【问题讨论】:

    标签: node.js web-scraping


    【解决方案1】:

    问题在于代码.msg-nickname 的那部分是在客户端生成的。所以如果你想抓取它,你需要知道数据来自哪个请求,然后执行那个请求。

    cheerio 只能解析请求响应中的内容。

    另一种选择是使用puppeteer,这将允许您等待页面完全加载,包括服务器端渲染、ajax 请求...

    const puppeteer = require('puppeteer');
    
    (async() => {
            const browser = await puppeteer.launch();
    
            const page = await browser.newPage();
    
            await page.goto(url);
    
            // waitForSelector can be added, depending on your needs
            // but if there isn't any user, it will wait until it timesout
            // which may not be desired
            // await page.waitForSelector('.msg-nickname');
    
            const messages = await page.evaluate(() => {
                    return Array.from(document.querySelectorAll('.msg-nickname'))
                            .map(item => item.innerText);
            });
    
            console.log(messages);
    })();
    

    根据昵称的加载方式,您可能需要连接到page.on('response'),或更改脚本的逻辑,但我将其留给您。

    【讨论】:

    • 使用await page.waitFor('.msg-nickname');这一行如何确保页面正确加载?
    • 问题是,该选择器并不总是存在,如果没有用户连接,它会等到它超时,使脚本慢得多。每个scraper都是独一无二的,所以有时你想用await page.waitForSelector('.msg-nickname'),有时你不用,这种情况下最好还是不用。
    • 我在代码中添加了注释,但在这种情况下不需要。
    • 你需要每隔一段时间运行它并推送到消息,可能使用 websockets 而不是像你正在做的 http 请求。
    • 哦,我明白了,谢谢你的回答!我要学习更多来做到这一点
    猜你喜欢
    • 2020-05-09
    • 1970-01-01
    • 2020-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-15
    • 1970-01-01
    相关资源
    最近更新 更多