Skip to content

Retrieve XPath and CSS selectors from elements selected in Playwright

License

Notifications You must be signed in to change notification settings

alexferrari88/playwright-DOMPath

Repository files navigation

Playwright DOMPath 🎭

MIT License NPM Version lgtm Code Quality GitHub Last Commit

This library implements the ChromeDevTools DOMPath functionality in Playwright.

This means that you can retrieve the CSS selector or the XPath of any element you select in your Playwright code.

🐍 Python version here: https://github.com/alexferrari88/playwright-dompath-py

Installation 📦

Install with npm

  npm install playwright-dompath

API Reference 📚

cssPath

cssPath: (elHandle: Playwright.ElementHandle | Playwright.Locator, optimized?: boolean) => Promise<string>

xPath

xPath: (elHandle: Playwright.ElementHandle | Playwright.Locator, optimized?: boolean) => Promise<string>

Usage 🔧

Just import the cssPath or xPath from this module:

import { cssPath, xPath } from "playwright-dompath";

Then use either function by passing it the element you previously selected (as ElementHandle or Locator):

const searchBar = await page.$('input[name="q"]');
console.log("CSS Path:", await cssPath(searchBar));
console.log("XPath:", await xPath(searchBar));

Since these functions return a promise, make sure to await the call (of course, you can also use the .then syntax instead. You do you.)

Full Example 🎁

import { chromium } from "playwright";
import { cssPath, xPath } from "playwright-dompath";

  const url = "https://google.com";
  const browser = await chromium.launch();
  const context = await browser.newContext();
  const page = await context.newPage();
  await page.goto(url);
  const searchBar = await page.$('input[name="q"]');
  console.log("CSS Path:", await cssPath(searchBar));
  console.log("XPath:", await xPath(searchBar));
  }
  await browser.close();
};

Which will output (class names may vary for you):

CSS Path: body > div.L3eUgb > div.o3j99.ikrT4e.om7nvf > form > div:nth-child(1) > div.A8SBwf > div.RNNXgb > div > div.a4bIc > input
XPath: /html/body/div[1]/div[3]/form/div[1]/div[1]/div[1]/div/div[2]/input

Used by

  • ScrapeBlocks: scraping automation framework based on Playwright

TODO ✅

  • Improve functions' speed
  • Increase tests coverage (include edge cases)
  • Add better error handling

Contributing 🤝🏼

Feel free to fork this repo and create a PR. I will review them and merge if ok.

The above todos can be a very good place to start.

Acknowledgements 🤗

License 📝

MIT