当前位置: 代码迷 >> python >> Python美丽汤在html中插入注释
  详细解决方案

Python美丽汤在html中插入注释

热度:30   发布时间:2023-06-27 21:56:00.0

我正在尝试使用漂亮的汤在html中插入评论,我想在关闭头部之前插入它,我正在尝试类似的操作

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

它是在</head>之前插入,但该值会得到实体编码的&lt;!-- #mycomment --&gt; Beautiful Soup文档标签,但是我应该如何直接插入注释。

实例化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>
  相关解决方案