Beautiful Soup - NavigableString() Method



Method Description

The NavigableString() method in bs4 package is the constructor method for NavigableString class. A NavigableString represents the innermost child element of a parsed document. This method casts a regular Python string to a NavigableString. Conversely, the built-in str() method coverts NavigableString object to a Unicode string.

Syntax

NavigableString(string)

Parameters

  • string − an object of Python's str class.

Return Value

The NavigableString() method returns a NavigableString object.

Example 1

In the code below, the HTML string contains an empty <b> tag. We add a NavigableString object in it.

html = """
<p><b></b></p>
"""
from bs4 import BeautifulSoup, NavigableString

soup = BeautifulSoup(html, 'html.parser')
navstr = NavigableString("Hello World")
soup.b.append(navstr)
print (soup)

Output

<p><b>Hello World</b></p>

Example 2

In this example, we see that two NavigableString objects are appended to an empty <b> tag. The tag responds to strings property instead of string property. It is a generator of NavigableString objects.

html = """
<p><b></b></p>
"""
from bs4 import BeautifulSoup, NavigableString

soup = BeautifulSoup(html, 'html.parser')
navstr = NavigableString("Hello")
soup.b.append(navstr)
navstr = NavigableString("World")
soup.b.append(navstr)
for s in soup.b.strings:
   print (s, type(s))

Output

Hello <class 'bs4.element.NavigableString'>
World <class 'bs4.element.NavigableString'>

Example 3

Instead of strings property, if we access the stripped_strings property of <b> tag object, we get a generator of Unicode strings i.e. str objects.

html = """
<p><b></b></p>
"""
from bs4 import BeautifulSoup, NavigableString

soup = BeautifulSoup(html, 'html.parser')
navstr = NavigableString("Hello")
soup.b.append(navstr)
navstr = NavigableString("World")
soup.b.append(navstr)
for s in soup.b.stripped_strings:
   print (s, type(s))

Output

Hello <class 'str'>
World <class 'str'>
Advertisements