In Puppeteer, how can I check if, for example, #idProductType
exists and if not, set producttype
to ""
? I tried many many things but it doesn't work.
const urls = [myurls, ...]
const productsList = [];
for (let i = 0; i < urls.length; i++) {
const url = urls[i];
await Promise.all([
page.goto(url),
page.waitForNavigation({ waitUntil: 'networkidle0' }),
]);
let products = await page.evaluate(() => {
//here i want to test if #idProductType exists do :
let producttype = document.querySelector('#idProductType').innerText;
//else
let producttype = "";
//and same thing for other selectors
let productsubtype = document.querySelector('#idProductSubType').innerText;
let product = document.querySelector('#idProduct').innerText;
let description = document.querySelector('td.js-orderModelVer').innerText;
let reference = document.querySelector('td.text-nowrap').innerText;
let prixpub = document.querySelector('td.text-nowrap.text-right.js-pricecol-msrp').innerText;
let dispo = document.querySelector('td.text-nowrap.text-center.js-pricecol-availability').innerText;
let retire = document.querySelector('td.js-retired-filler-cell').innerText;
let results = [];
results.push({
producttype: producttype,
productsubtype: productsubtype,
product: product,
description: description,
reference: reference,
prixpub: prixpub,
dispo: dispo,
retire: retire
})
return results
})
productsList.push(products);
}
Once we navigate to a webpage, we have to interact with the webelements available on the page like clicking a link/button, entering text within an edit box, and so on to complete our automation test case. For this, our first job is to identify the element.
To Fix check if an element exists on the page in Playwright. js, try { await page. waitForSelector(selector, { timeout: 5000 }) // ...`enter code here` } catch (error) {`enter code here` console. log("The element didn't appear.") }
return innerText or empty string if not found:
let productType = await page.evaluate(() => {
let el = document.querySelector(".foo")
return el ? el.innerText : ""
})
You can use page.$(selector) which is similar to document.querySelector(selector)
let producttype = (await page.$('#idProductType')) || "";
Puppeteer throws an error when could not find a matched element.
So to confirm the existence,
try {
await page.$(selector)
// Does exist
} catch {
// Does not
}
Or to make whether it exists a flag
const exists = await page.$eval(selector, () => true).catch(() => false)
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