无法使用剧作家读取有效选择器的 属性 null 的 innerText
Cannot read property innerText of null for valid selector using playwright
此脚本应该检索 DOM 元素的 innerText,元素选择器是
('div[class=QzVHcLdwl2CEuEMpTUFaj]')
并且我已经手动测试了选择器并在 REPL 中调用了 getSharePrice
函数,该函数也有效。
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 的原因。
在我的评估块之前添加 await page.waitForSelector('div[class=QzVHcLdwl2CEuEMpTUFaj]')
解决了这个问题。看起来问题是由尚未加载的元素引起的
此脚本应该检索 DOM 元素的 innerText,元素选择器是
('div[class=QzVHcLdwl2CEuEMpTUFaj]')
并且我已经手动测试了选择器并在 REPL 中调用了 getSharePrice
函数,该函数也有效。
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 的原因。
在我的评估块之前添加 await page.waitForSelector('div[class=QzVHcLdwl2CEuEMpTUFaj]')
解决了这个问题。看起来问题是由尚未加载的元素引起的