Sure, I can update the script to organize the datalist data into a proper table format within the TSV file. Specifically, I'll structure it so that:
- The datalist data is represented as a separate table in the TSV output.
- The first row of this table will be headers, e.g., "Datalist ID", "Option Value", and "Option Text".
- Each subsequent row will represent an individual
<option> element, with the "Datalist ID" column indicating which <datalist> it belongs to.
This way, the output will be aligned as a table, making it easier to read and process in tools like spreadsheets.
Here's the updated Python script:
import sys
from bs4 import BeautifulSoup
# Define input and output file paths
html_file_path = 'table.html'
tsv_file_path = 'table.tsv'
try:
# Read the HTML file
with open(html_file_path, 'r', encoding='utf-8') as f:
html_content = f.read()
except FileNotFoundError:
print(f"Error: Input file '{html_file_path}' not found.", file=sys.stderr)
sys.exit(1)
except Exception as e:
print(f"Error reading file '{html_file_path}': {e}", file=sys.stderr)
sys.exit(1)
# Parse the HTML content
try:
soup = BeautifulSoup(html_content, 'lxml')
except Exception as e:
print(f"Error parsing HTML: {e}", file=sys.stderr)
sys.exit(1)
# Capture all content types
tsv_lines = []
# 1. First, capture table data (as before)
tables = soup.find_all('table')
for i, table in enumerate(tables):
if len(tables) > 1:
tsv_lines.append(f"# --- Data from 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('\r', '').replace('\t', ' ')
row_data.append(cell_text)
tsv_lines.append('\t'.join(row_data))
# 2. Now, capture all <datalist> groups and structure as a table
datalists = soup.find_all('datalist')
datalist_rows = [] # List to hold rows for the datalist table
if datalists:
for datalist in datalists:
datalist_id = datalist.get('id', 'Unnamed Datalist') # Use ID as the group identifier
options = datalist.find_all('option')
for option in options:
value = option.get('value', '') # Get the 'value' attribute
text = option.get_text(strip=True) # Get the visible text
datalist_rows.append([datalist_id, value, text]) # Append as a row: [ID, Value, Text]
# Now, add the datalist table to tsv_lines
if datalist_rows: # Only add if there are rows
tsv_lines.append("\n# --- Datalist Table ---") # Section header
tsv_lines.append("Datalist ID\tOption Value\tOption Text") # Header row for the table
for row in datalist_rows:
tsv_lines.append('\t'.join(row)) # Each row as tab-separated values
# Write the TSV output to a file
try:
with open(tsv_file_path, 'w', encoding='utf-8') as f:
f.write('\n'.join(tsv_lines))
print(f"Successfully converted data from '{html_file_path}' to '{tsv_file_path}'.")
except Exception as e:
print(f"Error writing output file '{tsv_file_path}': {e}", file=sys.stderr)
sys.exit(1)
Explanation of Changes
-
Data Collection for Datalists:
- I created a list called
datalist_rows to store the data for the datalist table.
- For each
<datalist>, I loop through its <option> elements and create a row as a list: [datalist_id, option_value, option_text].
- This collects all options into a structured format, where each row represents one option, and the datalist ID is repeated for each option in that group.
-
Output Structure in TSV:
- After processing the original tables, I add a section header:
# --- Datalist Table --- to separate it visually.
- Then, I add a header row for the datalist table:
Datalist ID\tOption Value\tOption Text.
- Finally, I add each row from
datalist_rows as a tab-separated line.
-
Example Output:
If your HTML contains something like this:
<table>
<tr><td>Cell1</td><td>Cell2</td></tr>
</table>
<datalist id="fruits">
<option value="apple">Apple</option>
<option value="banana">Banana</option>
</datalist>
<datalist id="vegetables">
<option value="carrot">Carrot</option>
<option value="lettuce">Lettuce</option>
</datalist>
The resulting TSV file (table.tsv) might look like this:
# --- Data from Table 1 ---
Cell1 Cell2
# --- Datalist Table ---
Datalist ID Option Value Option Text
fruits apple Apple
fruits banana Banana
vegetables carrot Carrot
vegetables lettuce Lettuce
- This creates a clean, aligned table for the datalists.
- In a spreadsheet program like Excel or Google Sheets, you can import the TSV file, and it will display as two distinct tables: one for the original HTML tables and one for the datalists.
How to Use This Script
- Save the code in a file, e.g.,
html_to_tsv.py.
- Ensure you have the required libraries: Run
pip install beautifulsoup4 lxml if you haven't already.
- Place
html_to_tsv.py and your table.html in the same directory.
- Run the script with:
python html_to_tsv.py.
- Check the generated
table.tsv file for the updated output.
If this doesn't quite match what you meant by "align them in a table using datalists as headers," could you provide more details (e.g., a specific example of how you'd like the output structured)? I'd be happy to refine it further!