找到評論

要在 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