Python美丽汤在html中插入注释

Dev*_*evC 2 html python beautifulsoup python-2.7

我正在尝试使用漂亮的汤在html中插入注释,我想在关闭头部之前插入它,我正在尝试这样的操作

soup.head.insert(-1,"<!-- #mycomment -->")
Run Code Online (Sandbox Code Playgroud)

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

ale*_*cxe 5

实例化一个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()
Run Code Online (Sandbox Code Playgroud)

印刷品:

<html>
 <head>
  <test1>
  </test1>
  <test2>
  </test2>
  <!-- #mycomment -->
 </head>
 <body>
  test
 </body>
</html>
Run Code Online (Sandbox Code Playgroud)