【问题标题】:Javascript Cannot read property 'innerText' of null - puppeteerJavascript无法读取null的属性'innerText' - puppeteer
【发布时间】:2019-12-16 10:38:22
【问题描述】:

使用此功能时有时会出现此错误:我的功能工作了 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
[...]

【问题讨论】:

  • 该错误表示您的'body > pre'查询没有得到结果并返回null。你需要考虑到这一点。

标签: javascript node.js puppeteer


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-31
    • 1970-01-01
    • 1970-01-01
    • 2020-12-01
    • 2013-03-21
    • 2019-08-05
    相关资源
    最近更新 更多