Python 用lxml.html替换元素

Python 用lxml.html替换元素,python,lxml,Python,Lxml,作为一个整体,我对lxml和HTML解析器相当陌生。 我想知道是否有办法用另一个元素替换树中的一个元素 例如,我有: body = """<code> def function(arg): print arg </code> Blah blah blah <code> int main() { return 0; } </code> """ doc = lxml.html.fromstring(body) codeblocks = doc.css

作为一个整体,我对lxml和HTML解析器相当陌生。 我想知道是否有办法用另一个元素替换树中的一个元素

例如,我有:

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)
我想按照这些思路做一些事情,但这会导致“TypeError”,因为“hilited”不是lxml.etree.\u元素

这是否可行


关于,

如果您是python HTML解析器的新手,您可以尝试一下,一个HTML/xml解析器,它可以让您使用。

关于lxml

doc.replace(块,hilited)

block是lxml的元素对象,hilited是字符串,不能替换它

有两种方法可以做到这一点

block.text=hilited 


我一直在四处搜索,我注意到BeautifulSoup通过replaceWith具有这种确切的功能,在lxml中是否有类似的功能?(如果不是的话,那没关系,不过我还是很感兴趣)再次感谢!啊,我明白了!这是有道理的。谢谢我刚刚看过BeautifulSoup,它似乎比lxml.html更适合我的使用。谢谢你的建议!
body=body.replace(block.text,hilited)