CSS SELECTORS - Using select() with CSS syntax
Python
#!/usr/bin/env python3
"""CSS SELECTORS - Using select() with CSS syntax"""
from bs4 import BeautifulSoup
html = """
<html><body>
<div class="container">
<p class="text">Paragraph 1</p>
<p class="text highlight">Paragraph 2</p>
<span id="info">Information</span>
</div>
<p class="text">Paragraph 3</p>
</body></html>
"""
soup = BeautifulSoup(html, 'html.parser')
print("CSS Selectors:")
print(f" .text: {len(soup.select('.text'))} elements")
print(f" #info: {soup.select_one('#info').string}")
print(f" .container .text: {len(soup.select('.container .text'))} elements")
print(f" .text.highlight: {soup.select_one('.text.highlight').string}")
for elem in soup.select('p.text'):
print(f" {elem.get('class')}: {elem.string}")