Jest to jeden sposób:
#!/usr/bin/env python2.6
from lxml.html import fromstring, tostring
from lxml.html import builder as E
fragment = """\
<div id="outer">
<div id="inner">This is div.</div>
</div>"""
div = fromstring(fragment)
print tostring(div)
# <div id="outer">
# <div id="inner">This is div.</div>
# </div>
div.replace(div.get_element_by_id('inner'), E.DIV('Hello ', E.B('world!')))
print tostring(div)
# <div id="outer">
# <div>Hello <b>world!</b></div></div>
Zobacz także: http://lxml.de/lxmlhtml.html#creating-html-with-the-e-factory
Edit: Więc powinienem przyznał wcześniej, że nie jestem wszystkim, co zna lxml. Spojrzałem krótko na dokumenty i źródła, ale nie znalazłem czystego rozwiązania. Być może ktoś bardziej znajomy zatrzyma się i wyprostuje nas oboje.
W międzyczasie, to wydaje się działać, ale nie jest dobrze przetestowany:
import lxml.html
content_tag = lxml.html.fromstring('<div>Goodbye.</div>')
content_tag.text = '' # assumes only text to start
for elem in lxml.html.fragments_fromstring('Hello <b>world!</b>'):
if type(elem) == str: #but, only the first?
content_tag.text += elem
else:
content_tag.append(elem)
print lxml.html.tostring(content_tag)
Edycja ponownie: a ta wersja usuwa tekst i dzieci
somehtml = 'Hello <b>world!</b>'
# purge element contents
content_tag.text = ''
for child in content_tag.getchildren():
content_tag.remove(child)
fragments = lxml.html.fragments_fromstring(somehtml)
if type(fragments[0]) == str:
content_tag.text = fragments.pop(0)
content_tag.extend(fragments)
Sposób, w jaki naprawdę próbujesz zmodyfikować strukturę DOM, byłby dodanie nowego węzła dla 'świata'. – katrielalex
Jak to zrobić? –