1

I started learning about Playwright Java. The code below I used page.querySelector().getAttribute() and page.locator().getAttribute() to get the path of the same image. They return the same string img/logos/Browsers.png.

What is the difference between querySelector() and locator()? Is querySelector() or locator() better?

try (Playwright playwright = Playwright.create()) {
    Browser browser = playwright.chromium()
        .launch(new BrowserType.LaunchOptions().setHeadless(false).setSlowMo(50));
    Page page = browser.newPage();
    page.navigate("https://playwright.dev/");


    String srcImage1 = page.querySelector("//*[@id=\"docusaurus_skipToContent_fallback\"]/main/center/img")
        .getAttribute("src");

    String srcImage2 = page.locator("//*[@id=\"docusaurus_skipToContent_fallback\"]/main/center/img")
        .getAttribute("src");


    System.out.println(srcImage1);
    System.out.println(srcImage2);
    browser.close();
}
Kepler452B
  • 130
  • 1
  • 1
  • 9

2 Answers2

2

querySelector will give you a pointer to the element found when querySelector is called. A locator will use that selector to find the element every time an action on that element is requested.

Using locators is recommended over query selectors.

On your small example, the result will be the same, but, following best practices will help you make your automation code more stable.

hardkoded
  • 18,915
  • 3
  • 52
  • 64
2

On top of @hardKoded's great answer ,something to add based on my experience working through UI elements in Playwright:

In my early usage of ElementHandle/query selector cases , I was getting many times stale element reference issues as the actual element was changed by the time of actual usage of the element.

This is the same issue which I faced in selenium webdriver for a very long time in the past.

Locator resolves from root one of the biggest issue of " Stale element reference" error of selenium webdriver.

When I started changing those element references to Locators , they got very stable as under the hood it was not making static reference but making the object reference in real time at the time of locator actions(like click) based on locator definitions.

Reference:https://developer.mozilla.org/en-US/docs/Web/WebDriver/Errors/StaleElementReference

Vishal Aggarwal
  • 1,929
  • 1
  • 13
  • 23