#!/usr/bin/env python3
from html.parser import HTMLParser
import markdown
import re
import sys
import os
def esc(code):
return f'\033[{code}m'
class MyHTMLParser(HTMLParser):
def handle_starttag(self, tag, attrs):
if tag == 'h1':
print(esc(33) + '# ', end='')
elif tag == 'h2':
print(esc(34) + '## ', end='')
elif tag == 'h3':
print(esc(35) + '### ', end='')
elif tag == 'a':
print(esc('36;1;4'), end='')
elif tag == 'li':
print('- ', end='')
else:
print(esc(0), end='')
def handle_endtag(self, tag):
print(esc(0), end='')
def handle_data(self, data):
print(data, end='')
text = sys.stdin.read()
html = markdown.markdown(text)
parser = MyHTMLParser()
parser.feed(html)
print()
print()
parser.close()
Note: this is my first attempt at a post here.
I'm trying to understand how html parsing works via this little highlight script I'm tinkering with.
Is this how I should properly parse HTML, or is there another better way to do this? I'm currently following this guide: https://docs.python.org/3/library/html.parser.html.
This seems to work except that I want to add numbered links to the <a> tags. [3]link so it would display like this. So it seems calls between
method handlers would need to keep track of how many times it has been called.
For some reason I thought html parsing would convert html into json or a dict that I could iterate through.
How should I think about parsing html and am I doing this correctly?