XPath-friendlier ElementTree namespace helper
The effbot's namespace helper is nice, but doesn't handle the simple xpath expressions that ElementTree supports. This variant of it does:
class NS:
def __init__(self, uri):
self.uri = uri
def __getattr__(self, tag):
return self.uri + tag
def __call__(self, path):
return "/".join((tag not in ("", ".", "*"))
and getattr(self, tag)
or tag
for tag in path.split("/"))
You can then do stuff like this:
>>> XHTML = NS("{http://www.w3.org/1999/xhtml}")
>>> tree.findall(XHTML(".//li"))
[...]
It helps.