该脚本应该检索 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 的原因。