如何找到具有指定文本字符串的注释

时间:2016-08-06 20:32:40

标签: python beautifulsoup robobrowser

我正在使用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 感谢

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