tags:

views:

447

answers:

2

Hello,

I'm fairly new to lxml and HTML Parsers as a whole. I was wondering if there is a way to replace an element within a tree with another element...

For example I have:

body = """<code> def function(arg): print arg </code> Blah blah blah <code> int main() { return 0; } </code> """

doc = lxml.html.fromstring(body)
codeblocks = doc.cssselect('code')

for block in codeblocks:
  lexer = guess_lexer(block.text_content())
  hilited = highlight(block.text_content(), lexer, HtmlFormatter())
  doc.replace(block, hilited)

I want to do something along those lines, but this results in a "TypeError" because "hilited" isn't an lxml.etree._Element.

Is this feasible?

Regards,

+1  A: 

If you're new to python HTML parsers, you might try out beutifulsoup, a html/xml parser, which lets you modify the parse tree easily.

The MYYN
I've just looked at BeautifulSoup, it seems like it might be a better fit then lxml.html for my uses. Thanks for the suggestion!
tsoporan
+1  A: 

Hi,

Regarding lxml,

In doc.replace(block, hilited)

block is the lxml's Element object, hilited is string, you cannot replace that.

There is 2 ways to do that

block.text=hilited

or

body=body.replace(block.text,hilited)
S.Mark
Ah I see! That makes sense. Thanks!
tsoporan