Ah, I see what's happening! Since <option> elements are nested within <datalist> elements (or other form elements), we need to structure them by their parent <datalist> to maintain context. Here's an improved version that groups <option> elements by their parent <datalist> and formats them properly in TSV:
import sys
from bs4 import BeautifulSoup
html_file_path = 'table.html'
tsv_file_path = 'table.tsv'
try:
with open(html_file_path, 'r', encoding='utf-8') as f:
html_content = f.read()
except FileNotFoundError:
print(f"Error: File '{html_file_path}' not found.", file=sys.stderr)
sys.exit(1)
try:
soup = BeautifulSoup(html_content, 'lxml')
except Exception as e:
print(f"Error parsing HTML: {e}", file=sys.stderr)
sys.exit(1)
tsv_lines = []
# Process tables (unchanged from previous script)
tables = soup.find_all('table')
for i, table in enumerate(tables):
if len(tables) > 1:
tsv_lines.append(f"# --- TABLE {i+1} ---")
rows = table.find_all('tr')
for row in rows:
cells = row.find_all(['td', 'th'])
row_data = []
for cell in cells:
cell_text = cell.get_text(separator=" ", strip=True)
cell_text = cell_text.replace('\n', ' ').replace('\t', ' ')
row_data.append(cell_text)
tsv_lines.append('\t'.join(row_data))
# Process datalists and their options
datalists = soup.find_all('datalist')
if datalists:
tsv_lines.append("\n# --- DATALISTS AND OPTIONS ---")
for dl_idx, datalist in enumerate(datalists, 1):
dl_id = datalist.get('id', f'datalist_{dl_idx}')
options = datalist.find_all('option')
if not options:
continue # Skip empty datalists
# Add header for this datalist
tsv_lines.append(f"# DATALIST {dl_id}")
# Add column headers
tsv_lines.append("DATALIST_ID\tOPTION_VALUE\tOPTION_TEXT")
for option in options:
value = option.get('value', '')
text = option.get_text(strip=True)
tsv_lines.append(f"{dl_id}\t{value}\t{text}")
# Separator between datalists
tsv_lines.append("")
# Write to TSV
try:
with open(tsv_file_path, 'w', encoding='utf-8') as f:
f.write('\n'.join(tsv_lines))
print(f"File saved to '{tsv_file_path}'")
except Exception as e:
print(f"Error writing TSV: {e}", file=sys.stderr)
sys.exit(1)
What Changed:
-
Datalist Grouping:
- Processes
<datalist> elements and their <option> children as groups
- Each datalist is given its own section with:
- A header indicating the datalist ID
- Column headers (
DATALIST_ID, OPTION_VALUE, OPTION_TEXT)
- Rows for each option with their value and text
-
Formatting:
- Each
<datalist> block is separated from others for clarity
- Options are now in three columns instead of one, providing context
-
ID Handling:
- Uses the
id attribute of <datalist> if present
- Falls back to
datalist_1, datalist_2, etc., if no ID exists
Example Output:
# --- DATALISTS AND OPTIONS ---
# DATALIST states
DATALIST_ID OPTION_VALUE OPTION_TEXT
states ca California
states ny New York
states tx Texas
# DATALIST countries
DATALIST_ID OPTION_VALUE OPTION_TEXT
countries us United States
countries ca Canada
countries uk United Kingdom
How to Use:
- Save this updated script as
html_to_tsv_v2.py
- Run it the same way as before:
python html_to_tsv_v2.py
This should now properly structure your <option> elements into columns and group them by their parent <datalist>. Let me know if you need further adjustments!