"""Учебный парсер первой HTML-таблицы. Только локальный файл."""
from html.parser import HTMLParser
from pathlib import Path
import csv
import sys
class TableParser(HTMLParser):
def __init__(self):
super().__init__(convert_charrefs=True)
self.rows = []
self.depth = 0
self.done = False
self.row = None
self.cell = None
def handle_starttag(self, tag, attrs):
if self.done:
return
if tag == 'table':
self.depth += 1
elif self.depth == 1 and tag == 'tr':
self.row = []
elif self.depth == 1 and tag in ('td', 'th') and self.row is not None:
self.cell = []
def handle_data(self, data):
if self.depth == 1 and self.cell is not None:
self.cell.append(data)
def handle_endtag(self, tag):
if self.done:
return
if self.depth == 1 and tag in ('td', 'th') and self.cell is not None:
self.row.append(' '.join(''.join(self.cell).split()))
self.cell = None
elif self.depth == 1 and tag == 'tr' and self.row is not None:
if self.row:
self.rows.append(self.row)
self.row = None
elif tag == 'table' and self.depth:
self.depth -= 1
if self.depth == 0:
self.done = True
def convert(source, destination):
parser = TableParser()
parser.feed(Path(source).read_text(encoding='utf-8'))
rows = parser.rows
if len(rows) < 2 or len(rows[0]) != 4 or any(len(r) != 4 for r in rows):
raise ValueError('Нужна таблица с заголовком, данными и четырьмя столбцами.')
# Числа и идентификаторы не преобразуются: пустое значение остается пустым.
with Path(destination).open('w', newline='', encoding='utf-8-sig') as f:
csv.writer(f, delimiter=';').writerows(rows)
return len(rows) - 1
if __name__ == '__main__':
source = sys.argv[1] if len(sys.argv) > 1 else 'catalog.html'
destination = sys.argv[2] if len(sys.argv) > 2 else 'result.csv'
try:
print(f'Готово: {convert(source, destination)} строки. Файл: {destination}')
except (OSError, ValueError) as exc:
raise SystemExit(f'Не удалось создать CSV: {exc}')