如何找到具有指定文本字符串的评论

How can I find a comment with specified text string

我正在使用 robobrowser 来解析一些 html 内容。我里面有一个BeautifulSoup。如何在

中找到具有指定字符串的评论
<html>
<body>
<div>
<!-- some commented code here!!!<div><ul><li><div id='ANY_ID'>TEXT_1</div></li>
<li><div>other text</div></li></ul></div>-->
</div>
</body>
</html>

事实上,如果我知道 ANY_ID,我需要得到 TEXT_1 谢谢

使用 text 参数并检查类型为 Comment。然后,再次用BeautifulSoup加载内容,通过id:

找到想要的元素
from bs4 import BeautifulSoup
from bs4 import Comment

data = """
<html>
<body>
<div>
<!-- some commented code here!!!<div><ul><li><div id='ANY_ID'>TEXT_1</div></li>
<li><div>other text</div></li></ul></div>-->
</div>
</body>
</html>
"""

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

soup_comment = BeautifulSoup(comment, "html.parser")
text = soup_comment.find("div", id="ANY_ID").get_text()
print(text)

打印 TEXT_1.