BeautifulSoup: .contents Example

Syntax

element.contents

.contents example

from bs4 import BeautifulSoup

# Html source
html = """
<div>
<h2>Recent Posts:</h2>
<li><a href="/post/beautifulsoup-how-to-use-head-examples/">Beautifulsoup: How to use .head Examples</a></li>
<li><a href="/post/how-to-solve-modulenotfounderror-no-module-named-whois/">How to solve ModuleNotFoundError: No module named &#39;whois&#39;</a></li>
<li><a href="/post/python-how-to-use-whois-with-example/">Python: How to use whois() with example</a></li>
<li><a href="/post/beautifulsoup-get_text-example/">Beautifulsoup: get_text() Example</a></li>
<li><a href="/post/beautifulsoup-soupname-example/">BeautifulSoup: soup.name Example</a></li>
</div>
"""

# Parse
soup = BeautifulSoup(html, 'html.parser')

# Find div
el = soup.find('div')

# Print each element inside div
for e in el.contents:
    print(e)

Output:

<h2>Recent Posts:</h2>


<li><a href="/post/beautifulsoup-how-to-use-head-examples/">Beautifulsoup: How to use .head Examples</a></li>


<li><a href="/post/how-to-solve-modulenotfounderror-no-module-named-whois/">How to solve ModuleNotFoundError: No module named 'whois'</a></li>


<li><a href="/post/python-how-to-use-whois-with-example/">Python: How to use whois() with example</a></li>


<li><a href="/post/beautifulsoup-get_text-example/">Beautifulsoup: get_text() Example</a></li>


<li><a href="/post/beautifulsoup-soupname-example/">BeautifulSoup: soup.name Example</a></li>