A Python script for testing XPath expressions
I often find myself wanting to quickly test XPath expressions, so I whipped up a quick script to do so. Usage is simple:
$ cat test.html
<html>
<body>
Hello ${name}.
<div id="foo">Foo</div>
<form id="login">
<label for="username">Username: </label> <input id="username" />
</form>
</body>
</html>
<html>
<body>
Hello ${name}.
<div id="foo">Foo</div>
<form id="login">
<label for="username">Username: </label> <input id="username" />
</form>
</body>
</html>
$ xpathsh test.html '//form[@id="login"]/label[@for="username"]/text()'
Username:
And here's the script itself:
import sys
import optparse
from lxml import etree
parser = optparse.OptionParser(usage='usage: %prog <file> <xpath>')
options, args = parser.parse_args()
if len(args) < 2:
parser.error('Need at least a file and an X-Path.')
file = args.pop(0)
xpath = args.pop(0)
tree = etree.parse(open(file))
for match in tree.xpath(xpath):
try:
text = etree.tostring(match)
except TypeError:
text = str(match)
print text.strip()
import optparse
from lxml import etree
parser = optparse.OptionParser(usage='usage: %prog <file> <xpath>')
options, args = parser.parse_args()
if len(args) < 2:
parser.error('Need at least a file and an X-Path.')
file = args.pop(0)
xpath = args.pop(0)
tree = etree.parse(open(file))
for match in tree.xpath(xpath):
try:
text = etree.tostring(match)
except TypeError:
text = str(match)
print text.strip()


