I’m attempting to scrape a website using puppeteer and that requires me to fill in a date field with the date a week from when its executed. I used a date object to get the date a week in the future then created 3 constants (changed to variables for troubleshooting), and tried to use page.$eval
to fill the date field. However whenever page.$eval
runs it throws an error saying the variables are undefined.
I’ve tried swapping constant’s for variables, console logging the variables (which log correctly), swapping the order of the variables within $eval
.
Below is the code:
const pageToday = await page.content();
const weekAway = new Date(Date.now() + 604800000);
var wYear = weekAway.getFullYear();
var wMonth = (weekAway.getMonth() + 1).toString().padStart(2, "0");
var wDay = weekAway.getDate().toString().padStart(2, "0");
console.log(wMonth, wYear, wDay);
await page.$eval(
"#ctl00_cp_dtbDate",
(el) => (el.value = `${wMonth}/${wDay}/${wYear}`),
);
const pageWeek = await page.content();
await browser.close();
The target html element is: <input type="date" id="ctl00_cp_dtbDate" name="ctl00$cp$dtbDate" value="2024-10-22" class="" size="11" style="width:110px;" data-dashlane-rid="cf2be948f7a04438" data-dashlane-classification="date">
and here is the error:
node:internal/process/promises:394
triggerUncaughtException(err, true /* fromPromise */);
^
Error [ReferenceError]: wMonth is not defined
at $eval ($eval at /Users/nikolai/Developer/Digital Tech/daymap/server/server.js:167:14, <anonymous>:0:24)
at #evaluate (/Users/nikolai/Developer/Digital Tech/daymap/server/node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/ExecutionContext.js:386:56)
at async ExecutionContext.evaluate (/Users/nikolai/Developer/Digital Tech/daymap/server/node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/ExecutionContext.js:273:16)
at async IsolatedWorld.evaluate (/Users/nikolai/Developer/Digital Tech/daymap/server/node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/IsolatedWorld.js:99:16)
at async CdpJSHandle.evaluate (/Users/nikolai/Developer/Digital Tech/daymap/server/node_modules/puppeteer-core/lib/cjs/puppeteer/api/JSHandle.js:142:20)
at async CdpElementHandle.evaluate (/Users/nikolai/Developer/Digital Tech/daymap/server/node_modules/puppeteer-core/lib/cjs/puppeteer/api/ElementHandle.js:337:20)
at async CdpElementHandle.$eval (/Users/nikolai/Developer/Digital Tech/daymap/server/node_modules/puppeteer-core/lib/cjs/puppeteer/api/ElementHandle.js:491:24)
at async CdpFrame.$eval (/Users/nikolai/Developer/Digital Tech/daymap/server/node_modules/puppeteer-core/lib/cjs/puppeteer/api/Frame.js:444:20)
at async CdpPage.$eval (/Users/nikolai/Developer/Digital Tech/daymap/server/node_modules/puppeteer-core/lib/cjs/puppeteer/api/Page.js:447:20)
at async /Users/nikolai/Developer/Digital Tech/daymap/server/server.js:167:3