-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhtmlparse1.py
63 lines (50 loc) · 1.32 KB
/
htmlparse1.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
from html.parser import HTMLParser
example_html = '''
<html>
<head>
<title>HTML Parser - I</title>
</head>
<body data-modal-target class='1'>
<h1 class="header">HackerRank</h1>
<br id="main"/>
</body>
</html>
'''
class MyHTMLParser(HTMLParser):
def handle_starttag(self, tag, attrs):
'''
print(f' Found start tag: {tag}')
if attrs:
print(f' Found attributes: {attrs}')
'''
print(f'Start : {tag}')
for k, v in attrs:
print(f'-> {k} > {v}')
def handle_endtag(self, tag):
# print(f' Found end tag: {tag}')
print(f'End : {tag}')
# Empty tags:
def handle_startendtag(self, tag, attrs):
'''
print(f' Found an empty tag: {tag}')
if attrs:
print(f' Found attributes: {attrs}')
'''
print(f'Empty : {tag}')
for k, v in attrs:
print(f'-> {k} > {v}')
def main():
parser = MyHTMLParser()
lines = int(input())
for _ in range(lines):
parser.feed(input())
# Alternatively, collect all input and then parse:
# html += input()
# parser.feed(html)
#
# Need to explicitly close?
# parser.close()
# Example:
# parser.feed(example_html)
if __name__ == '__main__':
main()