The script I provided focuses on parsing <table> elements and their contents (<tr>, <td>, <th>), but doesn't inherently handle <option> elements, which are typically found within <select> tags and are part of form elements.
If you want to capture <option> elements, you'll need to modify the script to specifically look for and extract those. Here's an updated version that will capture <option> elements:
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 <option> elements
options = soup.find_all('option')
if options:
tsv_lines.append("\n# --- Option Elements ---")
for option in options:
# Extract value and text of each option
value = option.get('value', '')
text = option.get_text(strip=True)
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)
Key changes:
- Added a new section to find and extract all
<option> elements
- For each
<option>, it captures:
- The
value attribute (if present)
- The text content of the option
- Writes these to the TSV file after the table data
- Adds a section header to distinguish option data
This script will now:
- Capture all table data as before
- Find all
<option> elements in the HTML
- Extract their values and text
- Write them to the TSV file with a tab separator
The output will look something like:
# --- Data from Table 1 ---
(table data)
# --- Option Elements ---
value1 Option Text 1
value2 Option Text 2
...
Would you like me to explain any part of the script in more detail?