Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 222
Rakesh Vidya Chandra Avatar asked Jun 08 '15 14:06

Rakesh Vidya Chandra


People also ask

How do I use beautifulsoup4 in Python?

To use beautiful soup, you need to install it: $ pip install beautifulsoup4 . Beautiful Soup also relies on a parser, the default is lxml . You may already have it, but you should check (open IDLE and attempt to import lxml). If not, do: $ pip install lxml or $ apt-get install python-lxml .


1 Answers

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 + *")
like image 89
alecxe Avatar answered Sep 27 '22 19:09

alecxe