I try to scrap an element on a website and display it on localhost with Puppeteer (1). But when this element changes, I would like to refresh data without opening a new browser/page with Puppeteer and only when element changes (2).
For my example, I use www.timeanddate.com and the element is time (hours and minutes). For moment, only first part works. I don't have solution for second one.
Please find below, my code.
app.js
var app = require('express')();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
var puppeteer = require('puppeteer');
app.get('/', function(req, res) {
res.render('main.ejs');
});
server.listen(8080);
let scrape = async () => {
var browser = await puppeteer.launch({headless: true});
var page = await browser.newPage();
await page.goto('https://www.timeanddate.com/worldclock/personal.html');
await page.waitFor(300);
//await page.click('#mpo > div > div > div > div.modal-body > div.form-submit-row > button.submit.round.modal-privacy__btn');
var result = await page.evaluate(() => {
return document.getElementsByClassName('c-city__hrMin')[0].innerText;
});
return result;
};
io.sockets.on('connection', function (socket) {
scrape().then((value) => { // it tooks time, a few seconds while page is loading.
console.log(value);
socket.emit('refresh', value);
});
});
main.ejs
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>What time is it?</title>
<style>
a {text-decoration: none; color: black;}
</style>
</head>
<body>
<h1>Welcome !</h1>
<div id="time">loading</div>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:8080');
socket.on('refresh', function (value) {
$('#time').html(value);
});
</script>
</body>
</html>
I try Fiverr but awful experience. I hope it will better here :)
Thank you for helping me.