Calendars:Networked Media Calendar/Networked Media Calendar/16-03-2011 -Event 1: Difference between revisions
Line 14: | Line 14: | ||
* [[Finding capitalized words]] | * [[Finding capitalized words]] | ||
* [[Extracting parts of an HTML document]] | |||
=== Working with lxml === | === Working with lxml === |
Revision as of 13:58, 16 March 2011
11-18 | Nicolas Maleve - Thematic Project
Cookbook Recipes for Goodiff Workshop
Working with lxml
Extracting the text contents of a node (lxml)
The itertext method of a node can be useful.
for t in node.itertext():
print t
text = "".join(list(node.itertext()))
Turning part of a page back into code (aka serialization) (lxml)
Imagine you want to print out the full code of part of a page. Use lxml.etree.tostring. This converts any node back into source code -- a process called serialization.
htmlsource="<html><body><p>Example page.</p><p>More stuff with <i>markup</i>.</p></body></html>"
htmlparser = html5lib.HTMLParser(tree=html5lib.treebuilders.getTreeBuilder("lxml"), namespaceHTMLElements=False)
page = htmlparser.parse(htmlsource)
selector = lxml.cssselect.CSSSelector("p")
p = selector(page)[1]
print lxml.etree.tostring(p)