问题描述
我正在尝试使用漂亮的汤在html中插入评论,我想在关闭头部之前插入它,我正在尝试类似的操作
soup.head.insert(-1,"<!-- #mycomment -->")
它是在</head>
之前插入,但该值会得到实体编码的<!-- #mycomment -->
。
Beautiful Soup文档标签,但是我应该如何直接插入注释。
1楼
实例化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>