1

该脚本应该检索 DOM 元素的 innerText,元素选择器是 ('div[class=QzVHcLdwl2CEuEMpTUFaj]'),我已经手动测试了选择器并getSharePrice在 REPL 中调用了该函数,该函数也可以工作。

const { chromium } = require('playwright');
const util = require('util');
const setTimeoutPromise = util.promisify(setTimeout);

(async () => {
  const userDataDir = 'path'
  const browser = await chromium.launchPersistentContext(userDataDir, {headless: false }); 
  const page = await browser.newPage();
  await page.goto('https://robinhood.com', {timeout: 60000, waitUntil: 'domcontentloaded'});

  await getSharePrice(page)

  await setTimeoutPromise(1000);
  await browser.close();
})();


async function getSharePrice(page) {
    const price = await page.evaluate(() => {
        return {
            price: document.querySelector('div[class=QzVHcLdwl2CEuEMpTUFaj]').innerText.replace(/\D/g,'')
        }
    });
    console.log(price)
  }

出于某种原因,我收到一个(node:59324) UnhandledPromiseRejectionWarning: Error: Evaluation failed: TypeError: Cannot read property 'innerText' of null错误,不知道为什么。

我唯一能想到的是该元素尚未加载,导致它评估为 null 这就是无法调用 innerText 的原因。

4

1 回答 1

2

await page.waitForSelector('div[class=QzVHcLdwl2CEuEMpTUFaj]')在我的评估块之前添加解决了这个问题。看起来问题是由尚未加载的元素引起的

于 2020-08-11T22:37:16.337 回答