Javascript无法读取null的属性“ innerText”-puppeteer

时间:2019-12-14 23:41:50

标签: javascript node.js puppeteer

在使用此功能时有时会收到此错误:我的功能工作2/3次,但是请纠正它。我正在使用puppeteer导航并检查我的代理是否正常工作。

无法将属性'innerText'设置为null

请如何解决...

这是我的代码。

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];

错误代码:

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

1 个答案:

答案 0 :(得分:0)

您可以在调用评估函数之前添加waitForSelector

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