xpathplaywrightwebautomation

Unable to locate an element using xpath


This website has a menu item placed horizontally. I am trying to locate the element "Makeup" from the menu item using below XPath:

.categorymenu li:nth-child(1)

But no success.

Please, can someone help with a simple XPath with an explanation?


Solution

  • .categorymenu li:nth-child(1) isn't an XPath, it's a CSS selector. Neither XPath or CSS selectors are considered good practice in Playwright tests because they're heavily coupled to non-user visible behavior.

    Here's the preferred approach, following user-visible, accessible locators:

    import {expect, test} from "@playwright/test"; // ^1.46.1
    
    test("clicking the Makeup button navigates to the makeup page", async ({
      page,
    }) => {
      const url = "https://automationteststore.com";
      await page.goto(url, {waitUntil: "commit"});
      const description = page.getByText(
        "All your makeup needs, from foundation to eye shadow"
      );
      await expect(description).toBeHidden();
      await page.getByRole("link", {name: "Makeup"}).click();
      await expect(description).toBeVisible();
    });
    

    Now, if you're scraping this site, XPath and CSS selectors are less of a concern, but even here, I'd still use the user-visible approach since nth is liable to break if the page changes, and [href*='36'] also feels pretty arbitrary and brittle.