kel.o
kel.o

Reputation: 139

Cannot read property innerText of null for valid selector using playwright

This script is supposed to retrieve the innerText of a DOM element, the elements selector is ('div[class=QzVHcLdwl2CEuEMpTUFaj]') and I've hand-tested the selector and called the getSharePrice function in the REPL which also works.

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)
  }

for some reason, I am getting a (node:59324) UnhandledPromiseRejectionWarning: Error: Evaluation failed: TypeError: Cannot read property 'innerText' of null error, not sure why.

The only thing that I could come up with is that the element hasn't been loaded yet, causing it to evaluate to null which is why innerText can't be called.

Upvotes: 1

Views: 3322

Answers (1)

kel.o
kel.o

Reputation: 139

adding await page.waitForSelector('div[class=QzVHcLdwl2CEuEMpTUFaj]') before my evaluate block fixed this. Looks like the issue was caused by the element not being loaded yet

Upvotes: 2

Related Questions