Skip to content

SCRAPING TO CSV - Extracting table to CSV

Python
#!/usr/bin/env python3
"""SCRAPING TO CSV - Extracting table to CSV"""
from bs4 import BeautifulSoup
import csv
import tempfile
import os
html = """
<table>
<tr><th>Name</th><th>Age</th><th>City</th></tr>
<tr><td>Alice</td><td>30</td><td>NYC</td></tr>
<tr><td>Bob</td><td>25</td><td>LA</td></tr>
<tr><td>Charlie</td><td>35</td><td>Chicago</td></tr>
</table>
"""
soup = BeautifulSoup(html, 'html.parser')
print("Table to CSV:")
table = soup.find('table')
rows = table.find_all('tr')
csv_file = os.path.join(tempfile.gettempdir(), 'output.csv')
with open(csv_file, 'w', newline='') as f:
    writer = csv.writer(f)
    for row in rows:
        cells = row.find_all(['th', 'td'])
        writer.writerow([cell.string for cell in cells])
print(f"  Saved to: {csv_file}")
with open(csv_file, 'r') as f:
    print(f"  Content:\n{f.read()}")
os.remove(csv_file)