I'm trying to get data from a webpage using Playwright in TypeScript. I have a section of code where I want to extract information from multiple elements matching a certain locator.
However, I'm unsure whether to use Playwright's locator().all() method or evaluateAll() with querySelector. Both "just work", but I heard someone say don't use querySelector use locators.
Just to confirm that I'm using Playwright library, not @playwright/test.
Here's the code that uses a locator:
const ids = []; for (const id of await page.locator("div.ids").all()) { const id = await id.locator("span.id").first().textContent(); // Idk if this look ok or not but this's the only way I can come up with // because some time span.a will not exist and cause timeout const a = (await id.locator("span.a").count()) > 0 ? await id.locator("span.a").first().textContent() : null; idms.push({id, a}); } Here's the code that also use locator first but then use evaluateAll() and querySelector()
const ids = await page.locator("div.ids").evaluateAll((ids) => ids.map((id) => { const id = id.querySelector("span.id")?.textContent; const a = id.querySelector("span.a")?.textContent ?? null; return {id, a}; }) );
evaluteAllruns in the browser, so it's ok to usequerySelectorthere.