Gniax
Gniax

Reputation: 75

Javascript Cannot read property 'innerText' of null - puppeteer

Getting this error sometimes while using this function: My function works 2/3 times but I'd like to correct it pls. I'm using puppeteer to navigate and check if my proxy is working.

Cannot set property 'innerText' of null

How to fix it please...

Here's my code.

let proxyValidity = waiting("Checking proxy Validity", 800);
    try {
      await LOG('Trying to validate IP using an API');
      await page.goto(ipValidityUrl, { waitUntil: "load", timeout: 30000  });
    } catch (err) {
      await LOG('Error occured during loading IP validation API');
      await page.close();
      await closeBrowser(browser);
      stopWaiting(proxyValidity, (stdClrs.FgRed + "ERROR"));

      return {
        errorId: 3,
        msg: 'Unknown Proxy Error',
        error: err
      };
    }
    await LOG('IP validation URL loaded');

    let proxyInfo = await page.evaluate(() => {
      let div = document.querySelector('body > pre');
      console.log(div);
      jsonObject = JSON.parse(div.innerText);
      key = Object.keys(jsonObject);
      console.log(jsonObject[key]);
      return jsonObject[key];     
    })
    await LOG(`Proxy information recorded: ${proxyInfo}`);

    await LOG('Checking for validity of IP');
    let isValid = defaultData.proxyAllowedCountries.find((element) => { 
      return (proxyInfo[0] == element) 
    }) == proxyInfo[0];

The error code:

UnhandledPromiseRejectionWarning: Error: Evaluation failed: TypeError: Cannot read property 'innerText' of null
    at __puppeteer_evaluation_script__:4:35
[...]

Upvotes: 1

Views: 1387

Answers (1)

hardkoded
hardkoded

Reputation: 21597

You could add a waitForSelector before calling the evaluate function

await page.waitForSelector('body > pre');
await page.evaluate(...);

Upvotes: 3

Related Questions