Issue
I am trying to insert a comment in html using beautiful soup, I want to insert it before head closure, I am trying something like this
soup.head.insert(-1,"<!-- #mycomment -->")
It's inserting before </head>
but the value gets entity encoded <!-- #mycomment -->
. Beautiful Soup documentation speaks about inserting a tag but how should I insert a comment as it is.
Solution
Instantiate a Comment
object and pass it to insert()
.
Demo:
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()
prints:
<html>
<head>
<test1>
</test1>
<test2>
</test2>
<!-- #mycomment -->
</head>
<body>
test
</body>
</html>
Answered By - alecxe
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.