Im honestly curious why this method exists? Playwright auto-waits for things to be visible or loaded typically. So why would we ever need to call page.waitForSelector("locator")
?
I understand if we are waiting for a specific state, but I see a lot of example code using this method thrown around randomly......but I can't quite figure out why it would be necessary in a normal circumstance?
According to the docs for waitForSelector
, it's never necessary:
Discouraged. Use web assertions that assert visibility or a locator-based
locator.waitFor()
instead. Read more about locators.Playwright automatically waits for element to be ready before performing an action. Using Locator objects and web-first assertions makes the code wait-for-selector-free.
Playwright started out largely as a rewrite of Puppeteer for Microsoft. Puppeteer relies on page.$
, page.$eval
, page.waitForSelector
and ElementHandles to do most of its work. These are lower-level, single-purpose functions could be thought of as the primitive building blocks of browser automation. Playwright has diverged, and at the current time has deprecated or discouraged most of the Puppeteer-inherited API in favor of locators.
Locators have auto-waiting and strictness capabilities and operate at a higher level than the Puppeteer-style operations. Locators improve readability and reliability by combining waits and actions (like .click()
, .type()
, .textContent()
, .inputValue()
, .evaluate()
, .count()
, .waitFor()
, etc) into a single atomic step. When an action is fired on a locator, Playwright always waits and re-selects the freshest element from the DOM, helping to avoid stale handles and race conditions.
Almost always, when you're waiting for a selector to exist, you'll want to take an action on it, so although you can use page.locator("foo").waitFor()
as a locator-first translation of page.waitForSelector("foo")
, you'll usually use page.locator("foo").click()
or another, more specific action than .waitFor()
. In other words, .click()
and all other actions basically have a .waitFor()
baked into them.
You haven't shown any examples, so this is rather hand-wavey and general, but I'd guess that the examples are likely outdated and can be re-written with equivalent locators, as with basically all of the deprecated/discouraged shorthand locators like page.textContent()
, page.click()
, page.inputValue()
(etc).