I’m trying check if elements are available on a page from within a function, if the element is on the page, good, continue with the code, if not, log the error.
Using the try puppeteer page, here is what I tried:
const browser = await puppeteer.launch();
const page = await browser.newPage();
const check = element => {
try {
await page.waitFor(element, {timeout: 1000});
} catch(e) {
console.log("error : ", e)
await browser.close();
}
}
await page.goto('https://www.example.com/');
check("#something");
console.log("done")
await browser.close();
I get Error running your code. SyntaxError: Unexpected identifier
. I debugged a bit and it seems that page
within the check
function is the unexpected identifier. So I tried to pass it in with force like this:
const browser = await puppeteer.launch();
const page = await browser.newPage();
const check = (element, page) => {
try {
await page.waitFor(element, {timeout: 1000});
} catch(e) {
console.log("error : ", e)
await browser.close();
}
}
await page.goto('https://www.example.com/');
check("#something", page);
console.log("done")
await browser.close();
but I get the same Error running your code. SyntaxError: Unexpected identifier
error...
What am I doing wrong?
You can use this variant to check if the element is in the page or not.
if (await page.$(selector) !== null) console.log('found');
else console.log('not found');
Now back to your code, it's throwing error because of this function is not async
,
const check = async element => { // <-- make it async
try {
await page.waitFor(element, {timeout: 1000});
} catch(e) {
console.log("error : ", e)
await browser.close();
}
}
Anytime you call await
, it must be inside an async
function. You cannot call await everywhere. So your check function should be called like this,
await check("#something", page);
So altogether we can rewrite the code snippet this way, you can go ahead and try this one.
const browser = await puppeteer.launch();
const page = await browser.newPage();
const check = async(element, page) => (await page.$(element) !== null); // Make it async, return true if the element is visible
await page.goto('https://www.example.com/');
// now lets check for the h1 element on example.com
const foundH1 = await check("h1", page);
console.log(`Element Found? : ${foundH1}`);
// now lets check for the h2 element on example.com
const foundH2 = await check("h2", page);
console.log(`Element Found? : ${foundH2}`);
await browser.close();
Also async functions will return promises, so you have to catch that promise or use another await. Read more about async await here:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With