Python Beautiful Soup 在HTML中插入注释

3 投票
1 回答
1710 浏览
提问于 2025-04-17 22:18

我想用Beautiful Soup在HTML中插入一个注释,想把它放在标签关闭之前。我尝试了以下方法:

soup.head.insert(-1,"<!-- #mycomment -->")

它确实是在</head>之前插入了,但插入的内容变成了实体编码,显示为&lt;!-- #mycomment --&gt;。Beautiful Soup的文档中提到过如何插入标签,但我该怎么插入一个注释呢?

1 个回答

10

创建一个 Comment 对象,然后把它传递给 insert() 方法。

示例:

from bs4 import BeautifulSoup, Comment


data = """<html>
<head>
    <test1/>
    <test2/>
</head>
<body>
    test
</body>
</html>"""

soup = BeautifulSoup(data)
comment = Comment(' #mycomment ')
soup.head.insert(-1, comment)

print soup.prettify()

输出结果:

<html>
 <head>
  <test1>
  </test1>
  <test2>
  </test2>
  <!-- #mycomment -->
 </head>
 <body>
  test
 </body>
</html>

撰写回答