Xpath builder in Python
Question: I'm building relatively complicated xpath expressions in Python, in order to
pass them to selenium. However, its pretty easy to make a mistake, so I'm
looking for a library that allows me to build the expressions without messing
about with strings. For example, instead of writing

    
    
    locator='//ul[@class="comment-contents"][contains(., "West")]/li[contains(., "reply")]
    

I could write something like:

    
    
    import xpathbuilder as xpb
    locator = xpb.root("ul")
                 .filter(attr="class",value="comment-contents")
                 .filter(xpb.contains(".", "West")
                 .subclause("li")
                 .filter(xpb.contains (".", "reply"))
    

which is maybe not as readable, but is less error-prone. Does anything like
this exist?


Answer: though this is not exactly what you want.. you can use css selector

    
    
    ...
    import lxml.cssselect
    csssel = 'div[class="main"]'
    selobj = lxml.cssselect.CSSSelector(csssel)
    elements = selobj(documenttree)
    

generated XPath expression is in `selobj.path`

    
    
    >>> selobj.path
    u"descendant-or-self::div[@class = 'main']"
    

