forked from mikeizbicki/html_validator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
HTML_Validator.py
57 lines (45 loc) · 1.36 KB
/
HTML_Validator.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
#!/bin/python3
def validate_html(html):
'''
This function performs a limited version of html validation by checking whether every opening tag has a corresponding closing tag.
>>> validate_html('<strong>example</strong>')
True
>>> validate_html('<strong>example')
False
'''
tags = _extract_tags(html)
s = []
balanced = True
index = 0
for index in range(len(tags)):
html_tag = tags[index]
if '/' not in html_tag:
s.append(html_tag)
else:
if s == []:
balanced = False
else:
top = s.pop()
if top[1:] != html_tag[2:]:
balanced = False
if balanced and s == []:
return True
else:
return False
def _extract_tags(html):
'''
This function returns a list of all the html tags contained in the input string, stripping out all text not contained within angle brackets.
>>> _extract_tags('Python <strong>rocks</strong>!')
['<strong>', '</strong>']
'''
tags = []
for x in range(len(html)):
if html[x] == '<':
html_tag = ''
i = x
while html[i] != '>':
html_tag += html[i]
i += 1
html_tag += '>'
tags.append(html_tag)
return tags