0

So i'm doing some web scraping of a bunch of products on a page & my code works fine as long as the elements are there, though sometimes when a product is out of stock and an element isn't present on a page I get the following error.

I've tried to put some kind of "If statement" inside the map object though can't get it to work.

//This code works if all the elements are present on the page const productsOnPage = await page.$$eval('.tile-product', as => as.map(productContainer => ({ productTitle: productContainer.querySelector('h3').innerText.trim(), })) ); //I want something like this to handle the null values const productsOnPage = await page.$$eval('.tile-product', as => as.map(productContainer => ({ if ( productContainer.querySelector('h3').innerText.length <= 0 || null ) { productTitle: productContainer.querySelector('h3').innerText.trim(), } else { productTitle: '', } })) ); 

If null I expect:

productTitle: ""; 

but i'm getting:

Error: Evaluation failed: TypeError: Cannot read property 'innerText' of null 

2 Answers 2

1

You can use ternary operator, E.g

const productsOnPage = await page.$$eval('.tile-product', as => as.map(productContainer => ({ productTitle: productContainer.querySelector('h3') ? productContainer.querySelector('h3').innerText.trim() : ''; })) ); 
Sign up to request clarification or add additional context in comments.

Comments

0

People already answered with the correct solution. But I believe an explanation is needed. On your if statement productContainer.querySelector('h3').innerText.length you're checking the length of the innerText property from querySelector('h3'). But you must verify if the querySelector('h3') exists before reading its properties.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.