Beautifulsoup: Getting a new line when I tried to access the soup.head.next_sibling value with Beautifulsoup4

984 views Asked by At

I am trying an example from the BeautifulSoupDocs and found it acting weird. When I try to access the next_sibling value, instead of the "body" a '\n' is coming in to picture.

html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><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
soup = BeautifulSoup(html_doc)
soup.head.next_sibling
u'\n'

I am using latest version of beautifulSoup4. i.e 4.3.2. Please help me out. Thanks in advance.

2

There are 2 answers

1
alecxe On BEST ANSWER

There are 3 kinds of objects that BeautifulSoup "sees" in the HTML:

  • Tag
  • NavigableString
  • Comment

When you get .next_sibling it returns you the next object after the current which, in your case, is a text node (NavigableString). Explained in the documentation here.

If you want to find the next Tag after the current, use find_next_sibling(), or, with specifying the tag name: find_next_sibling("body").

You can also use the "next sibling" CSS Selector:

soup.select("head + *")
0
Ajay On

try this

soup.head.find_next_sibling()

or

soup.head.next_sibling.next_sibling