When you're running into problems with evaluate
, the first steps are to add a listener to browser console.log
s and try the code in the browser yourself.
Let's try running the code in the browser itself, without Puppeteer, so we can see if there are any errors:
const results = document.querySelectorAll("div");
dates = {};
if (results.length) { // unnecessary; if results.length is 0, the loop won't run
for (var i = 0; i < results.length; i++) {
dates.push(results[i].getAttribute('aria-label'));
}
}
console.log(dates);
<div aria-label="foobar">baz</div>
This gives Uncaught TypeError: dates.push is not a function
. You probably meant dates
to be an array, not an object:
const results = document.querySelectorAll("div");
dates = [];
for (var i = 0; i < results.length; i++) {
dates.push(results[i].getAttribute('aria-label'));
}
console.log(dates);
<div aria-label="foobar">baz</div>
Putting that into Puppeteer, we can shorten it to:
const puppeteer = require("puppeteer");
let browser;
(async () => {
browser = await puppeteer.launch();
const [page] = await browser.pages();
await page.setContent('<div aria-label="foobar">baz</div>');
const arias = await page.evaluate(() => Array.from(
document.querySelectorAll("div"),
e => e.getAttribute("aria-label")
));
// or:
//const arias = await page.$$eval("div", els =>
// els.map(e => e.getAttribute("aria-label"))
//);
console.log(arias); // => [ 'foobar' ]
})()
.catch(err => console.error(err))
.finally(async () => await browser.close())
;
I don't have a flatpickr handy so I'm assuming your selector is valid if substituted for "div"
in the above code, along with the actual site you're scraping.