Beautiful Soup – children Property


Beautiful Soup – children Property



”;


Method Description

The Tag object in Beautiful Soup library has children property. It returns a generator used to iterate over the immediate child elements and text nodes (i.e. Navigable String).

Syntax


Tag.children

Return value

The property returns a generator with which you can iterate over direct children of the PageElement.

Example 1


from bs4 import BeautifulSoup, NavigableString

markup = ''''''
   <div id="Languages">
      <p>Java</p> <p>Python</p> <p>C++</p>
   </div>
''''''
soup = BeautifulSoup(markup, ''html.parser'')
tag = soup.div
children = tag.children
for child in children:
   print (child)

Output


<p>Java</p>

<p>Python</p>

<p>C++</p>

Example 2

The soup object too bears the children property.


from bs4 import BeautifulSoup, NavigableString

markup = ''''''
   <div id="Languages">
      <p>Java</p> <p>Python</p> <p>C++</p>
   </div>
''''''
soup = BeautifulSoup(markup, ''html.parser'')

children = soup.children
for child in children:
   print (child)

Output


<div id="Languages">
<p>Java</p> <p>Python</p> <p>C++</p>
</div>

Example 3

In the following example, we append NavigableString objects to the <p> Tag and get the list of children.


from bs4 import BeautifulSoup, NavigableString

markup = ''''''
   <div id="Languages">
      <p>Java</p> <p>Python</p> <p>C++</p>
   </div>
''''''
soup = BeautifulSoup(markup, ''html.parser'')
soup.p.extend([''and'', ''JavaScript''])
children = soup.p.children
for child in children:
    print (child)

Output


Java
and
JavaScript

Advertisements

”;

Leave a Reply

Your email address will not be published. Required fields are marked *