From Page interactions | Puppeteer:
Locators is the recommended way to select an element and interact with it. Locators encapsulate the information on how to select an element and they allow Puppeteer to automatically wait for the element to be present in the DOM and to be in the right state for the action. You always instantiate a locator using the page.locator() or frame.locator() function. If the locator API doesn’t offer a functionality you need, you can still use lower level APIs such as page.waitForSelector() or ElementHandle.
This table sums up my understanding on the difference between locator()
and $()
:
Page method |
Returned class | Wait for element to present in the DOM? | Need await ? |
Input methods |
---|---|---|---|---|
locator() |
Locator |
Yes (retry until success or timeout) | No | Only have click , hover , scroll , |
$() |
ElementHandle |
No | Yes | Various |
I have two questions:
- If
locator()
waits for element to present in the DOM, then isn’t that it has to haveawait
? Similarly, if$()
doesn’t wait, then isn’t that it doesn’t needawait
? - Why does
$()
, a method that doesn’t wait for elements to present in DOM, have more input methods than the one waits for them?