我正在使用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 感谢
答案 0 :(得分:0)
使用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
。