Related Articles

Related Articles

descendants generator – Python Beautifulsoup
  • Last Updated : 25 Oct, 2020

descendants generator is provided by Beautiful Soup which is a web scraping framework for Python. Web scraping is the process of extracting data from the website using automated tools to make the process faster. The .contents and .children attribute only consider a tag’s direct children. The descendants generator is used to iterate over all of the tag’s children, recursively. Each child is going to be the tag element for the elements and NavigableString for the strings.

Syntax: 

 tag.descendants 

Below given examples explain the concept of descendants generator in Beautiful Soup. 
Example 1: In this example, we are going to get the descendants of an element.

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Import Beautiful Soup
from bs4 import BeautifulSoup
  
# Create the document
doc = "<body><b> Hello world </b><body>"
  
# Initialize the object with the document
soup = BeautifulSoup(doc, "html.parser")
  
# Get the body tag
tag = soup.body
  
# Print all the descendants of tag
for descendant in tag.descendants:
    print(descendant)

chevron_right


Output: 



<b> Hello world </b>
 Hello world 
<body></body>

Example 2: In this example, we are going to see the type of descendants.

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Import Beautiful Soup
from bs4 import BeautifulSoup
  
# Create the document
doc = "<body><b> Hello world </b><body>"
  
# Initialize the object with the document
soup = BeautifulSoup(doc, "html.parser")
  
# Get the body tag
tag = soup.body
  
# Print the type of the descendants of tag
for descendant in tag.descendants:
    print(type(descendant))

chevron_right


Output: 

<class 'bs4.element.Tag'>
<class 'bs4.element.NavigableString'>
<class 'bs4.element.Tag'>

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :