xml.etree.ElementTree:如何替换like "innerHTML"?

xml.etree.ElementTree: How to replace like "innerHTML"?

我想替换 html 页面的 <h1> 标签。

但是标题的内容可以是HTML(不只是字符串)

我要插入foo <b>bold</b> bar

输入:

start 
<h1 class="myclass">bar <i>italic</i></h1>
end

期望的输出:

start 
<h1 class="myclass">foo <b>bold</b> bar</h1>
end

如何用 Python 解决这个问题?

parser = HTMLParser(namespaceHTMLElements=False)
etree = parser.parse('start <h1 class="myclass">bar <i>italic</i></h1> end')
for h1 in etree.findall('.//h1'):
    for sub in h1:
        h1.remove(sub)
    html = parser.parse('foo <b>bold</b> bar')
    body = html.find('.//body')
    for sub in body:
        h1.append(sub)
    h1.text = body.text
print(ElementTree.tostring(etree))

使用 html:

page="""start 
<h1 class="myclass">bar <i>italic</i></h1>
end
"""
import htql
x = htql.query(page, "<h1>:tx &replace('foo <b>bold</b> bar') ")[0][0]

你得到:

>>> x
'start \n<h1 class="myclass">foo <b>bold</b> bar</h1>\nend\n'