P粉7980104412023-08-17 17:50:42
await page.waitForSelector(".Ip")
Only returns one element, not an array, so it cannot be looped. There should be a clear error message explaining the problem. Instead, use page.$$eval
(or if you want to try the latest locator API) to extract the data.
const puppeteer = require("puppeteer"); // ^21.0.2 const url = ""; let browser; (async () => { browser = await puppeteer.launch(); const [page] = await browser.pages(); await page.setViewport({width: 1000, height: 926}); await page.goto(url, {waitUntil: "domcontentloaded"}); // not really necessary const button = await page.waitForSelector("#onetrust-accept-btn-handler"); await button.click(); await page.waitForSelector(".Ip"); const content = await page.$$eval(".Ip", els => els.map(e => { const text = id => e.querySelector(`[id*=${id}]`).textContent.trim(); return { time: text("status-or-time"), home: text("home-team-name"), away: text("away-team-name"), homeTeamScore: +text("home-team-score"), awaitTeamScore: +text("away-team-score"), }; }) ); console.log(content); })() .catch(err => console.error(err)) .finally(() => browser?.close());
Note:
waitForSelector
. It is guaranteed to be the element, otherwise it will throw an exception if it is not found within the specified time. await elements[i].$(".Ip")
won't help you access anything because there is no ## inside the .Ip
element you already hold #.Ip.