Carol.Kar
Carol.Kar

Reputation: 5345

TypeError: Cannot read property 'innerText' of null

I am using "puppeteer": "^1.16.0",.

When trying to test my page I get the following error:

I am using the following code to check if a table has the correct data:

await page.evaluate(async () => {
        let arr = [];
        let grabFromRow = (row, child) => row
            .querySelector(`td:nth-child(${child})`)
            .innerText // ====> if a value is 'null', I get an error here!
            .trim();

        const rows = "#table > thead > tr"

        const t = document.querySelectorAll(rows)
        for (const r of t) {
            arr.push({
                date: grabFromRow(r, 1).trim(),    
                quarter: grabFromRow(r, 2).trim(),
                consensus_estimate: grabFromRow(r, 3).trim(), 
                reported_eps: grabFromRow(r, 4).trim(),
                gaap_eps: grabFromRow(r, 5).trim(),
                revenue_estimate: grabFromRow(r, 6).trim(),
                actual_revenue: grabFromRow(r, 7).trim(), 
            });
        }
        console.log(arr);

        return arr
    });

Any suggestions what I am doing wrong?

I appreciate your replies!

Upvotes: 0

Views: 1199

Answers (1)

epascarello
epascarello

Reputation: 207501

So you get the error because the element does not exist. If you are expecting it to exist, then you need to figure out what in your selector is wrong.

Your comment is making it appear that you expect it to not exist in certain cases. So then you need to break it up and make sure the element exists before you try to access it.

let grabFromRow = (row, child) => {
  const td = row
    .querySelector(`td:nth-child(${child})`)
  return td ? td.innerText.trim() : ''
}

or use a truthy check and set a default if you want it in one line

let grabFromRow = (row, child) =>
  (row.querySelector(`td:nth-child(${child})`) || {innerText : ''})
    .innerText // ====> if a value is 'null', I get an error here!
    .trim();

Upvotes: 2

Related Questions