html = """ <html><head><title>The Dormouse's story</title></head> <body> <p class="title" name="dromouse"><b>The Dormouse's story</b></p> <p class="story">Once upon a time there were three little sisters; and their names were <a href="http://example.com/elsie" class="sister" id="link1"><!-- Elsie --></a>, <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>; and they lived at the bottom of a well.</p> <p class="story">...</p> """
>>> from bs4 import BeautifulSoup >>> html = """ ... <html> ... <body> ... <p class="story"> ... Once upon a time there were three little sisters; and their names were ... <a href="http://example.com/elsie" class="sister" id="link1"> ... <span>Elsie</span> ... </a> ... Hello ... <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> ... and ... <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a> ... and they lived at the bottom of a well. ... </p> ... """ >>> soup = BeautifulSoup(html, 'lxml') >>> soup.a <a class="sister" href="http://example.com/elsie" id="link1"> <span>Elsie</span> </a> >>> soup.a.next_sibling '\n Hello\n ' >>> soup.a.previous_sibling '\n Once upon a time there were three little sisters; and their names were\n ' >>> soup.a.next_siblings <generator object PageElement.next_siblings at 0x1110e57c8> >>> soup.a.previous_siblings <generator object PageElement.previous_siblings at 0x1110e5de0> >>> for i in soup.a.previous_siblings: ... print(i) ...
Once upon a time there were three little sisters; and their names were >>> for i in soup.a.next_siblings: ... print(i) ...
Hello <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a> and <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>