找到评论

要在 BeautifulSoup 中查找注释,请使用 text(或最新版本中的 string )参数检查类型为 Comment

from bs4 import BeautifulSoup
from bs4 import Comment

data = """
<html>
    <body>
        <div>
        <!-- desired text -->
        </div>
    </body>
</html>
"""

soup = BeautifulSoup(data, "html.parser")
comment = soup.find(text=lambda text: isinstance(text, Comment))
print(comment)

打印 desired text