-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhtmlparsing
52 lines (41 loc) · 1.19 KB
/
htmlparsing
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
#
# Example file for parsing and processign HTML
#
from html.parser import HTMLParser
metacount = 0
class MyHTMLParser(HTMLParser):
def handle_coment(self, data):
print("Encountered comment: ", data)
pos = self.getpos()
print("\tAt line: ", pos[0], " position ", pos[1])
def handle_starttag(self, tag, attrs):
global metacount
if tag == 'meta':
metacount += 1
print("Encountered tag: ", tag)
pos = self.getpos()
print("\tAt line: ", pos[0], " position ", pos[1])
if attrs.__len__() > 0:
print("\tAttributes: ")
for a in attrs:
print("\t", a[0], "=", a[1])
def handle_endtag(self, tag):
print("Encountered tag: ", tag)
pos = self.getpos()
print("\tAt line: ", pos[0], " position ", pos[1])
def handle_data(self, data):
if(data.isspace()):
return
print("Encountered data: ", data)
pos = self.getpos()
print("\tAt line: ", pos[0], " position ", pos[1])
def main():
#instantiate the parser and feed it some HTML
parser = MyHTMLParser()
f = open("samplehtml.html")
if f.mode == 'r':
contents = f.read()
parser.feed(contents)
print("Meta tags found: " + str(metacount))
if __name__ == "__main__":
main()