Comments are displayed in the BeautifulSoup syntax tree, like any other node. For example, to find a comment with some comment text , and then print the previous <p> element that you could do:
from BeautifulSoup import BeautifulSoup, Comment soup = BeautifulSoup('''<html> <body> <p>paragraph 1</p> <p>paragraph 2</p> <p>paragraph 3</p> </body> </html>''') def right_comment(e): return isinstance(e, Comment) and e == 'some comment text' e = soup.find(text=right_comment) print e.findPreviousSibling('p')
... which will be printed:
<p>paragraph 2</p>
source share