Reputation: 21
in my sample js code
let targetXpath = 'xpath=//html/body/div[1]/div[2]/div[1]/div[1]/div/span[3]/div[2]/div[3]/div/div/div/div/div/div[2]/div/div/div[1]/h2/a/span'
let name1 = await page.locator(targetXpath).evaluate(node => node.innerText)
console.log(name1) // prints the name of the item being looked at on the xpath
edit: I should have noted I tried both statements separately. So if you comment out name1 and console.log(name1), And I was trying to do this on amazon searching for nvidia 3060
let nameDollar1 = await page.$(targetXpath)
console.log(nameDollar1) // prints null
How is playwright able to see this when calling evaluate but not able to see it when using $()?
Upvotes: 0
Views: 3394
Reputation: 3152
Locators are waiting for elements to appear and have strict mode (makes sure that there is only 1 element on the page with the given selector) enabled. Page.$ and Page.$$ on the other hand (some Playwright language bindings also call it querySelector and querySelectorAll) don't wait for the elements and also don't have strict mode enabled. Thats why its null in your case.
Keep also in mind that locators resolve the element when the action (click, fill, etc.) gets executed and $/$$ resolve the element when they are getting called. See here for more information: https://playwright.dev/docs/locators
General rule: Always use Locators.
Upvotes: 1