We don’t allow questions seeking recommendations for books, tools, software libraries, and more. 开发者_如何学编程You can edit the question so it can be answered with facts and citations.
Closed 5 years ago.
Improve this questionI'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?
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']"
You can use lxml.etree that allows to write code as the following:
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 …")
)
)
精彩评论