XPath to CSS Selector Converter

1.2.0 · active · verified Wed Apr 22

xpath-to-css is a JavaScript utility package designed to translate XPath expressions into equivalent CSS selectors. Originally conceived in Python for the `cssify` project by santiycr and later adapted to a JavaScript gist by Dither, this package by Jonathan Svenheden provides an npm-published, ES2015 and CommonJS-compatible solution. It is currently at version 1.2.0, with a release cadence that is likely infrequent, reflecting its stable utility nature rather than active feature development, given its last update was over two years ago. Its core differentiation lies in providing a readily accessible and battle-tested conversion tool for a specific web scraping and automation need, handling various common XPath patterns like ID, class, attribute, and positional selectors. Developers leverage it to bridge between systems that prefer CSS selectors (e.g., Playwright, Puppeteer) and sources that provide XPath (e.g., some browser developer tools, legacy systems).

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to import the `xPathToCss` function and convert a complex XPath expression to its CSS selector equivalent, along with simpler examples.

import xPathToCss from 'xpath-to-css';

const xPath = '//div[@id="foo"][2]/span[@class="bar"]//a[contains(@class, "baz")]//img[1]';
const css = xPathToCss(xPath);
console.log(css); // => 'div#foo:nth-of-type(2) > span.bar a[class*=baz] img:first-of-type'

const simpleXPath = '//h1';
const simpleCss = xPathToCss(simpleXPath);
console.log(simpleCss); // => 'h1'

const attributeXPath = '//input[@type="text"]';
const attributeCss = xPathToCss(attributeXPath);
console.log(attributeCss); // => 'input[type="text"]'

view raw JSON →