Im collecting titles and images from website into a human-readable format.
I use fs.writeFile
and options are:
- save as html (where its opened locally) or,
- have it sent to email by nodemailer.
Either way I need the info in table format in html. Top row = Title, Price, Image (displayed, not link). Columns =list of items.
I added in a portion to convert JSON to html table but its messing up. Now the script does not run. Error is document not defined (in table formation).
Separately, if theres any way to auto-send the list to emails daily without maintaining a server, kindly let me know too.
const puppeteer = require('puppeteer');
const fs = require('fs');
/* this gets the json data, all working ok */
async function newCam() {
const browser = await puppeteer.launch({ headless: false });
let page = await browser.newPage();
await page.goto('https://sg.carousell.com/search/products/?query=camera', { waitUntil: 'networkidle2' });
let results = [];
let elements = await page.$$('div.U-U');
for (let element of elements) {
let listTitle = await element.$eval('div.U-m', node => node.innerText.trim());
let listImg = await element.$eval('.U-p img', img => img.src);
let listPrice = await element.$eval('div.U-k :nth-child(1)', node => node.innerText.trim());
results.push({
'Title': listTitle,
'Img': listImg,
'Px': listPrice
});
}
await browser.close();
return results;
/* format json into table and feed into fs below */
// get header keys
var col = [];
for (var i = 0; i < results.length; i++) {
for (var key in results[i]) {
if (col.indexOf(key) === -1) { col.push(key); }
}
}
// create table
var table = document.createElement("table");
var tr = table.insertRow(-1); // insert header row.
for (var k = 0; k < col.length; k++) {
var th = document.createElement("th"); // fill header
th.innerHTML = col[k];
tr.appendChild(th);
}
// add json data as rows
for (var a = 0; a < results.length; a++) {
tr = table.insertRow(-1);
for (var f = 0; f < col.length; f++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = results[a][col[f]];
}
}
/* save to html on local drive with fs */
fs.writeFile('/data.html', table, (err) => {
if (err) throw err;
});
}
newCam();