Skip to content

COMPLEX CSS SELECTORS - Advanced selection

Python
#!/usr/bin/env python3
"""COMPLEX CSS SELECTORS - Advanced selection"""
from bs4 import BeautifulSoup
html = """
<html><body>
<div class="container">
    <p class="intro">Intro</p>
    <div class="content">
        <p class="text">Content para</p>
    </div>
</div>
<p class="text">Outside para</p>
</body></html>
"""
soup = BeautifulSoup(html, 'html.parser')
print("Complex CSS Selectors:")
print(f"  'div p': {[p.string for p in soup.select('div p')]}")
print(f"  'div > p': {[p.string for p in soup.select('div > p')]}")
print(f"  '.container .text': {soup.select_one('.container .text').string}")
print(f"  'p:nth-of-type(1)': {soup.select_one('p:nth-of-type(1)').string}")