cssselectvsuntangle
cssselect is a BSD-licensed Python library to parse CSS3 selectors and translate them to XPath 1.0 expressions.
XPath 1.0 expressions can be used in lxml or another XPath engine to find the matching elements in an XML or HTML document.
cssselect is used by other popular Python packages like parsel
and scrapy
but can also be used on it's own to generate
valid XPath 1.0 expressions for parsing HTML and XML documents in other tools.
Note that because XPath selectors are more powerful than CSS selectors this translation is only possible one way. Converting XPath to CSS selectors is impractical and not supported by cssselect.
untangle is a simple library for parsing XML documents in Python. It allows you to access data in an XML file as if it were a Python object, making it easy to work with the data in your code.
To use untangle, you first need to install it via pip by running pip install untangle``.
Once it is installed, you can use the
untangle.parse()`` function to parse an XML file and create a Python object.
For example:
import untangle
obj = untangle.parse("example.xml")
print(obj.root.element.child)
You can also pass a file-like object or a string containing XML data to the untangle.parse() function. Once you have an untangle object, you can access elements in the XML document using dot notation.
You can also access the attributes of an element by using attrib property, eg. `obj.root.element['attrib_name']`` untangle also supports xpath-like syntax to access the elements, obj.root.xpath("path/to/element")
It also supports iteration over the elements using obj.root.element.children
for child in obj.root.element.children:
print(child)
Example Use
from cssselect import GenericTranslator, SelectorError
translator = GenericTranslator()
try:
expression = translator.css_to_xpath('div.content')
print(expression)
'descendant-or-self::div[@class and contains(concat(' ', normalize-space(@class), ' '), ' content ')]'
except SelectorError as e:
print(f'Invalid selector {e}')
import untangle
obj = untangle.parse("example.xml")
print(obj.root.element.child)
# access attributes:
print(obj.root.element['attrib_name'])
# use xpath:
element = obj.root.xpath("path/to/element")