https://github.com/steambap/xpath-to-selector
convert xpath to css selector
https://github.com/steambap/xpath-to-selector
Last synced: 5 months ago
JSON representation
convert xpath to css selector
- Host: GitHub
- URL: https://github.com/steambap/xpath-to-selector
- Owner: steambap
- License: mit
- Created: 2020-09-28T07:18:00.000Z (over 5 years ago)
- Default Branch: main
- Last Pushed: 2023-03-28T06:46:52.000Z (about 3 years ago)
- Last Synced: 2025-11-16T17:08:19.149Z (7 months ago)
- Language: TypeScript
- Size: 194 KB
- Stars: 14
- Watchers: 1
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
- fucking-awesome-css - Xpath-to-selector - Convert xpath to css selector. (Miscellaneous / Editor's Draft :black_nib:)
- awesome-css - Xpath-to-selector - Convert xpath to css selector. (Miscellaneous / Editor's Draft :black_nib:)
README
# xpath-to-selector
[](https://github.com/steambap/xpath-to-selector/actions/workflows/main.yaml)
convert xpath to css selector
## install
> npm install --save-dev xpath-to-selector
## usage
```JavaScript
import xPath2Selector from "xpath-to-selector";
const xPath =
'//div[@id="foo"][2]/span[@class="bar"]//a[contains(@class, "baz")]//img[1]';
const css = xPath2Selector(xPath);
console.log(css); // => 'div#foo:nth-child(2) > span.bar a[class*=baz] img:nth-child(1)'
```
## why
In my one of my previous job I was working on a product that is similar to Cypress / Selenium. The product should allow the user to use either xpath or css selector, so I wrote a simple JavaScript convertor from xpath to css selector. This is an upgraded version of what I have at that time and it's rewritten in TypeScript.
The community already have [xpath-to-css](https://github.com/svenheden/xpath-to-css). But I think it would be nice to let others see my implementation if they don't like the Python and regexp based parser for xpath.
By using a recursive parser, it allows you to parser something that is very difficult to match in Regex, for example:
```JavaScript
import xPath2Selector from "xpath-to-selector";
const xPath =
'/html/body/form/input[@id="id_username" and position()=2]';
const css = xPath2Selector(xPath);
console.log(css); // => 'html > body > form > input#id_username:nth-child(2)'
```
## license
[MIT](LICENSE)