Search code examples
javascripttypescriptxpathcss-selectorsplaywright

How to locate an element by Xpath/CSS selectors using Playwright


How to locate an element by Xpath/CSS selectors using Playwright TS/JS?

There are many locators in Playwright (in comparison to Selenium) such as getByRole and getByText.

Is there any locator like getByCssSelector or getByXpath?


Solution

  • According to Playwright Docs about Locators

    ou can use page.locator() to create a locator that takes a selector describing how to find an element in the page. Playwright supports CSS and XPath selectors, and auto-detects them if you omit css= or xpath= prefix.

    // With Prefix
    await page.locator('css=button').click(); // CssSelector
    await page.locator('xpath=//button').click(); // Xpath
    
    // Without Prefix
    await page.locator('button').click(); // CssSelector
    await page.locator('//button').click(); // Xpath