I have no formal code training and this is my first attempt at a Javapscript project and it's incredibly frustrating to be hung up on such a simple problem now that I'm 99.9% done.
I've stitched together the following scraper code from https://www.codementor.io/johnnyb/how-to-write-a-web-scraper-in-nodejs-du108266t and adapted it to a different target website:
// Define the scrape function
function scrape(url, data, cb) {
// 1. Create the request
req(url, (err, body) => {
if (err) { return cb(err); }
// 2. Parse the HTML
let $ = cheerio.load(body)
, pageData = {}
;
// 3. Extract the data
Object.keys(data).forEach(k => {
pageData[k] = $(data[k]).text();
});
// Send the data in the callback
cb(null, pageData);
});
}
// Extract some data from a website
scrape("http://www.esbnyc.com/explore/tower-lights", {
// Get the website title (from the top header)
title: ".view-empty #page-title"
}, (err, data) => {
console.log(err || data);
});
And I was delighted to see it worked! The console log displayed (almost, I'd like to get rid of the 'title:' that precedes the scraped web text) exactly what I wanted and I figured it would be a cinch to add that information to a string.
Yet 3 hours later of fumbling around and trying all the wrong answers I realize I'm no closer to a solution. All I want is to save the information I'm seeing in the log (e.g. "Tonight, the Empire State Building will be lit in its signature white.") as a string in the form of a Const/Var/whatever. Yet the best I've been able to get so far is literally nothing or an 'undefined'.