我想做的是建立一个scrapingNodeJs 上的应用程序,它可以实时监控聊天并将某些消息存储在任何数据库中?
我想做的是以下内容,我想从聊天平台流中捕获数据,从而捕获一些有用的信息来帮助那些正在做流媒体服务的人;
但我不知道如何开始使用 NodeJs 来做到这一点,
到目前为止,我所能做的就是捕获消息的数据,但是我无法监控实时新消息,
在这方面有什么帮助吗?
到目前为止我做了什么:
服务器.js
var express = require('express');
var fs = require('fs');
var request = require('request');
var puppeteer = require('puppeteer');
var app = express();
app.get('/', function(req, res){
url = 'https://www.nimo.tv/live/6035521326';
(async() => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto(url);
await page.waitForSelector('.msg-nickname');
const messages = await page.evaluate(() => {
return Array.from(document.querySelectorAll('.msg-nickname'))
.map(item => item.innerText);
});
console.log(messages);
})();
res.send('Check your console!')
});
app.listen('8081')
console.log('Magic happens on port 8081');
exports = module.exports = app;
这样,我获取用户消息的昵称并将其放入一个数组中,我想让我的应用程序运行并在聊天中完成输入时自动接收新的昵称,
对这个挑战有什么帮助吗?
也许我需要使用 WebSocket
如果可能的话你应该使用API,聊天正在使用。尝试打开 Chrome 开发者工具中的网络选项卡,并尝试找出正在发生哪些网络请求。
如果这不可能,您可以使用MutationObserver监控 DOM 变化。通过以下方式公开函数page.exposeFunction然后听取相关变化。然后您可以将获得的数据插入数据库。
下面是一些可以帮助您入门的示例代码:
const puppeteer = require('puppeteer');
const { Client } = require('pg');
(async () => {
const client = new Client(/* ... */);
await client.connect(); // connect to database
const browser = await puppeteer.launch({ headless: false });
const [page] = await browser.pages();
// call a handler when a mutation happens
async function mutationListener(addedText) {
console.log(`Added text: ${addedText}`);
// insert data into database
await client.query('INSERT INTO users(text) VALUES($1)', [addedText]);
}
page.exposeFunction('mutationListener', mutationListener);
await page.goto('http://...');
await page.waitForSelector('.msg-nickname');
await page.evaluate(() => {
// wait for any mutations inside a specific element (e.g. the chatbox)
const observerTarget = document.querySelector('ELEMENT-TO-MONITOR');
const mutationObserver = new MutationObserver((mutationsList) => {
// handle change by checking which elements were added and which were deleted
for (const mutation of mutationsList) {
const { removedNodes, addedNodes } = mutation;
// example: pass innerText of first added element to our mutationListener
mutationListener(addedNodes[0].innerText);
}
});
mutationObserver.observe( // start observer
observerTarget,
{ childList: true }, // wait for new child nodes to be added/removed
);
});
})();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)