0

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

4

1 回答 1

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

于 2016-08-06T20:36:59.210 回答