Thank you for the clarification. If your <option> elements are grouped within <datalist> tags, we can adjust the script to properly handle these groupings and align the data correctly in the TSV file.
To achieve this:
- We'll first identify all
<datalist> elements.
- For each
<datalist>, we'll extract its associated options and ensure they are grouped together.
- We'll add a header for each
<datalist> to indicate which group the options belong to.
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 with their <option> elements
datalists = soup.find_all('datalist')
if datalists:
tsv_lines.append("\n# --- Datalist Groups ---")
for datalist in datalists:
# Get the 'id' attribute of the <datalist> as the group name
datalist_id = datalist.get('id', 'Unnamed Datalist')
tsv_lines.append(f"\n# Datalist ID: {datalist_id}")
# Extract all <option> elements within the <datalist>
options = datalist.find_all('option')
for option in options:
value = option.get('value', '') # Get the 'value' attribute of the <option>
text = option.get_text(strip=True) # Get the visible text of the <option>
tsv_lines.append(f"{value}\t{text}")
# 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
-
Identify <datalist> Elements:
- The script now looks for all
<datalist> tags in the HTML using soup.find_all('datalist').
- Each
<datalist> is treated as a group.
-
Group Options by <datalist>:
- For each
<datalist>, the script extracts its id attribute (or assigns "Unnamed Datalist" if no id is present) to label the group.
- All
<option> elements within the <datalist> are processed together.
-
Output Format:
- A header is added for each
<datalist> group to make it clear which options belong to which group.
- Each
<option> is written with its value and text content separated by a tab (\t).
Example Output
If your HTML contains something like this:
<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 will look like this:
# --- Data from Table 1 ---
(table data)
# --- Datalist Groups ---
# Datalist ID: fruits
apple Apple
banana Banana
# Datalist ID: vegetables
carrot Carrot
lettuce Lettuce
Key Points
- Each
<datalist> group is clearly labeled with its id or a default name.
- Options within each group are aligned in two columns:
value and text.
- The script handles multiple
<datalist> groups and ensures proper separation between them.
Let me know if this works for your use case or if you need further adjustments!