from bs4 import BeautifulSoup
html = """
<div id="root">
</div>
"""
# parse the root
root = BeautifulSoup(html)
# create the child
child = BeautifulSoup('<div id="child" />')
# create the grandchild under the child, and append grandchild to child
grandchild = child.new_tag('div', attrs={'id': 'grandchild'})
child.div.append(grandchild)
# create the child under the root, and append child to root
root.new_tag(child.html.contents[0].div)
root.div.append(child.html.contents[0].div)
您可以将另一个
soup
附加到标记。例如:印刷品:
这是一个相当复杂的代码,但这就是如何做到的:
请注意:
如果打印
root
:输出为:
这意味着
root
现在是一个完整的HTML文档。因此,如果您想使用
root
作为div,请确保使用root.div
访问它最后一行(
root.div.append
)清空child
,因此如果在执行最后一行后打印它:输出为:
相关问题 更多 >
编程相关推荐