Skip to content

Instantly share code, notes, and snippets.

@mnot
Created October 29, 2009 12:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mnot/221417 to your computer and use it in GitHub Desktop.
Save mnot/221417 to your computer and use it in GitHub Desktop.
libxslt_web.py: use XSLT on the "normal" Web
#!/usr/bin/env python2.4
"""
libxslt_web - XSLT Extension Functions for the HTML Web
This is a set of XSLT extension functions that give access to HTTP mechanisms and HTML
documents (even those that are invalid) on the Web.
In particular, it offers;
- GET and POST support, with control over the POST body and content-type
- Automatic HTTP cookie and redirect handling
- SSL (when supported by urllib2)
The functions exposed are:
get(uri) - GET the uri; returns a string of the response representation.
post(uri, body, [content-type]) - post the body to the URI; returns a string of
the response representation.
tidy_parse(instr) - parse html and return a nodeset.
to_string(node) - return the node serialised as a string.
form_encode(node) - return the arguments serialised as a urlencoded form.
Responses to HTTP methods return a nodeset with an arbitrary number of 'header' elements,
one for each HTTP response header, and a single 'body' element. The header element
has a single attribute, 'name', which contains the lowercased header field-name. For example;
<header name="cache-control">Private</header>
<header name="date">Tue, 18 Oct 2005 22:38:52 GMT</header>
<body>... body content here...</body>
Forms are similarly handled;
<arg name="username">my_username</arg>
<arg name="password">my_password</arg>
and passed to form_encode.
See the test() function for a demonstration.
Requires Python 2.4, libxml2, libxslt and mxTidy.
TODO:
- return respnose status
- PUT and DELETE
- authentication support (basic, digest)
- base64 of binary content (?)
"""
__license__ = """
Copyright (c) 2005 Mark Nottingham <mnot@pobox.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
__version__ = "0.2"
import string, urllib, urllib2, tempfile, cookielib
import libxml2, libxslt # http://xmlsoft.org/
from mx import Tidy # http://www.egenix.com/files/python/mxTidy.html
EXT_NS = "http://mnot.net/libxslt_web/1.0"
parse_options = libxml2.HTML_PARSE_RECOVER + libxml2.HTML_PARSE_NOERROR + libxml2.HTML_PARSE_NOWARNING
# set up cookie handling
cookie_policy = cookielib.DefaultCookiePolicy(rfc2965=True)
cookie_jar = cookielib.CookieJar(cookie_policy)
cookie_handler = urllib2.HTTPCookieProcessor(cookie_jar)
opener = urllib2.build_opener(cookie_handler)
urllib2.install_opener(opener)
def get(ctx, uri):
""" Extension function to perform a HTTP GET. """
if type(uri) == type([]):
node = libxml2.xmlNode(_obj=uri[0])
uri = node.getContent()
res = urllib2.urlopen(uri)
root = libxml2.newNode('response')
for name, value in res.headers.dict.items():
hdr = root.newTextChild(None, 'header', value)
hdr.setProp('name', name.lower())
root.newTextChild(None, 'body', res.read())
return [root]
def post(ctx, uri, body, content_type='application/x-www-form-urlencoded'):
""" Extension function to perform a HTTP POST. """
if type(uri) == type([]):
node = libxml2.xmlNode(_obj=uri[0])
uri = node.getContent()
if type(body) == type([]):
node = libxml2.xmlNode(_obj=body[0])
body = node.getContent()
headers = {'Content-Type': content_type}
req = urllib2.Request(uri, body, headers)
res = urllib2.urlopen(req).read()
root = libxml2.newNode('response')
for name, value in res.headers.dict.items():
hdr = root.newTextChild(None, 'header', value)
hdr.setProp('name', name.lower())
root.newTextChild(None, 'body', res.read())
return [root]
def tidy_parse(ctx, content):
""" Extension function to Tidy a string into a tree of XML nodes. """
if type(content) == type([]):
node = libxml2.xmlNode(_obj=content[0])
content = node.getContent()
tmp = tempfile.NamedTemporaryFile()
try:
content.replace("&nbsp;", " ")
content.replace("&nbsp", " ")
result = Tidy.tidy(content, output=tmp.file, output_xhtml=1, quote_ampersand=0, numeric_entities=0, output_error=0)
tmp.flush()
doc = libxml2.htmlReadFile(tmp.name, None, parse_options)
root = doc.getRootElement()
root.unlinkNode()
return [root]
finally:
tmp.close()
def to_string(ctx, content):
""" Extension function to serialise an XML node into a string. """
if type(content) == type([]):
node = libxml2.xmlNode(_obj=content[0])
content = node.getContent()
node = libxml2.xmlNode(_obj=content[0])
return str(node)
def form_encode(ctx, content):
""" Extension function to form-encode a string. """
args = []
if type(content) == type([]):
node = libxml2.xmlNode(_obj=content[0])
content = node.getContent()
for node in content:
arg = libxml2.xmlNode(_obj=node)
print "*", arg.name, arg.prop('name'), arg.getContent()
if arg.name != 'arg': continue
args.append((arg.prop('name'), arg.getContent()))
return urllib.urlencode(args)
libxslt.registerExtModuleFunction("tidy_parse", EXT_NS, tidy_parse)
libxslt.registerExtModuleFunction("to_string", EXT_NS, to_string)
libxslt.registerExtModuleFunction("get", EXT_NS, get)
libxslt.registerExtModuleFunction("post", EXT_NS, post)
libxslt.registerExtModuleFunction("form_encode", EXT_NS, form_encode)
def test():
styledoc = libxml2.parseDoc("""
<xsl:stylesheet version='1.0'
xmlns:xsl='http://www.w3.org/1999/XSL/Transform'
xmlns:web='http://mnot.net/libxslt_web/1.0'
xsl:exclude-result-prefixes='web'>
<xsl:template match='/'>
<xsl:variable name="form">
<arg name="a">1</arg>
<arg name="b">2</arg>
<arg name="c">3</arg>
</xsl:variable>
<xsl:variable name="raw" select="web:get('http://www.google.com/')"/>
<xsl:variable name="doc" select="web:tidy_parse($raw/body)"/>
<xsl:variable name="test" select="web:tidy_parse(web:to_string($doc))"/>
<a><xsl:value-of select="$doc/head/title"/></a>
<b><xsl:value-of select="$raw/header[@name='date']"/></b>
<c><xsl:value-of select="web:to_string($doc/head)"/></c>
<d><xsl:value-of select="$test/head/title"/></d>
<e><xsl:value-of select="web:form_encode($form)"/></e>
</xsl:template>
</xsl:stylesheet>
""")
style = libxslt.parseStylesheetDoc(styledoc)
doc = libxml2.parseDoc("<doc/>")
result = style.applyStylesheet(doc, {})
style.freeStylesheet()
doc.freeDoc()
print result
def run(instance, stylesheet, params={}):
style = libxslt.parseStylesheetFile(stylesheet)
doc = libxml2.parseFile(instance)
result = style.applyStylesheet(doc, params)
doc.freeDoc()
return result
def usage():
import sys
sys.stderr.write("%s instance stylesheet [param=value...]\n" % sys.argv[0])
sys.exit(1)
if __name__ == "__main__":
import sys
# test(); sys.exit(0) # uncomment to run test()
try:
instance, stylesheet = sys.argv[1:3]
except:
usage()
params = {}
for param in sys.argv[3:]:
try:
key, value = param.split('=', 1)
params[key] = value
except:
usage()
print run(instance, stylesheet, params)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment