Skip to content

WORKING WITH TABLES - Parsing HTML tables

Python
#!/usr/bin/env python3
"""WORKING WITH TABLES - Parsing HTML tables"""
from bs4 import BeautifulSoup
html = """
<table>
<tr><th>Name</th><th>Age</th></tr>
<tr><td>Alice</td><td>30</td></tr>
<tr><td>Bob</td><td>25</td></tr>
</table>
"""
soup = BeautifulSoup(html, 'html.parser')
print("Parsing Tables:")
table = soup.find('table')
rows = table.find_all('tr')
print(f"  Total rows: {len(rows)}")
for i, row in enumerate(rows):
    cells = row.find_all(['th', 'td'])
    values = [cell.string for cell in cells]
    print(f"    Row {i}: {values}")