Xpath creator in Python

I am creating relatively complex xpath expressions in Python to pass them to selenium. However, it's pretty easy to make a mistake, so I'm looking for a library that allows me to create expressions without interfering 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 may not be readable, but less error prone. Is there anything similar?

+4
source share
2 answers

although this is not quite what you want. You can use css selector

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

XPath generated expression is in selobj.path

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

You can use lxml.etree , which allows you to write code as follows:

 from lxml.builder import ElementMaker # lxml only ! E = ElementMaker(namespace="http://my.de/fault/namespace", nsmap={'p' : "http://my.de/fault/namespace"}) DOC = E.doc TITLE = E.title SECTION = E.section PAR = E.par my_doc = DOC( TITLE("The dog and the hog"), SECTION( TITLE("The dog"), PAR("Once upon a time, ..."), PAR("And then …") ), SECTION( TITLE("The hog"), PAR("Sooner or later …") ) ) 
0
source

All Articles