javaplaywrightplaywright-java

What's difference between page.querySelector() and page.locator() Playwright?


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();
}

Solution

  • 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.