0

Is it possible to convert complex CSS Selectors such as:

@[class="maintitle"] > .main-wrap #myid > .h1 bold

To XPath in Python 3 without using external libraries? Or with regex?

I'm currently able to convert

@[class="maintitle"]

to "//*[contains(@class,'maintitle')]" but cannot manage to create a global rule to convert these more complex selectors. Is it even possbile?

Edit: I can't use cssselect.

2 Answers 2

2

Try below XPath

//*[@class="maintitle"]/*[contains(@class, "main-wrap")]//*[@id="myid"]/*[contains(@class="h1")]//bold

If you need tool that can convert CSS to XPath for you, you can try lxml:

from cssselect import GenericTranslator
from lxml.etree import XPath

css_selector = """[class="maintitle"] > .main-wrap #myid > .h1 bold"""
print(XPath(GenericTranslator().css_to_xpath(css_selector)))

Output (looks weird, but...):

descendant-or-self::*[@class = 'maintitle']/*[@class and contains(concat(' ', normalize-space(@class), ' '), ' main-wrap ')]/descendant-or-self::*/*[@id = 'myid']/*[@class and contains(concat(' ', normalize-space(@class), ' '), ' h1 ')]/descendant-or-self::*/bold

Note that you might also need to add // at the beggining as:

print("//" + str(XPath(GenericTranslator().css_to_xpath(css_selector))))
Sign up to request clarification or add additional context in comments.

9 Comments

I need a global code in python 3 to convert the given css selector to an xpath. The selector above was just an example.
Andersson's better than any global code you could hope for. :-)
I know but I need a global code, not a specific one because my xpath vary
Is it possible to do it without cssselect? I'm can't to use it. I can use lxml.etree
cssselect should be installed separately from lxml. Try pip install cssselect. P.S. You cannot get required result without cssselect... I mean you cannot implement current solution without it.
|
0

the best way would be using lxml:

You can pass "//" as a param to XPath(GenericTranslator().css_to_xpath(css_selector)

something like this XPath(GenericTranslator().css_to_xpath(css_selector,"//") to avoid descendant-or-self:: at the beginning

1 Comment

This mostly looks like a rehash of the existing accepted answer from nearly four years ago. Please don't repeat answers. See How to Answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.