你只需要通過所有可用的意見進行迭代,看它是否是你所需要的一個條目,然後爲下面的元素顯示文本,如下所示:
from bs4 import BeautifulSoup, Comment
html = """
<html>
<body>
<p>p tag text</p>
<!--UNIQUE COMMENT-->
I would like to get this text
<!--SECOND UNIQUE COMMENT-->
I would also like to find this text
</body>
</html>
"""
soup = BeautifulSoup(html, 'lxml')
for comment in soup.findAll(text=lambda text:isinstance(text, Comment)):
if comment in ['UNIQUE COMMENT', 'SECOND UNIQUE COMMENT']:
print comment.next_element.strip()
這顯示如下:
I would like to get this text
I would also like to find this text
我剛纔正要這樣做。 +1 –
正是我所需要的。非常感謝你。 – LANshark