lxml retrieving odd items with cssselector
-
18-09-2019 - |
Question
In my test document I have a few classes labeled "item", currently I'm using the following to parse everything in the html file with this class with
Selection = html.cssselect(".item")
I'd like it to select all the odd items, like this in javascript using JQuery
Selection = $(".item:odd");
Trying that verbatim I get the following error
lxml.cssselect.ExpressionError: The psuedo-class Symbol(u'odd', 6) is unknown
I know this would be trivial to implement on my own, I was wondering if this is supported by lxml natively.
Solution
The "odd" and "even" features are part of a selector named "nth-child()"; take a look at the CSS selector specification for more details:
http://www.w3.org/TR/2001/CR-css3-selectors-20011113/#nth-child-pseudo
Therefore, you should be able to get exactly the behavior you want (and it works for me with CSSSelector here) with:
".item:nth-child(odd)"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow