-
Notifications
You must be signed in to change notification settings - Fork 0
/
htmlparsing.py
53 lines (42 loc) · 1.66 KB
/
htmlparsing.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
from html.parser import HTMLParser
import os
os.chdir("/workspace")
paragraphs = 0
# create a subclass of HTMLParser and override the handler methods
class MyHTMLParser(HTMLParser):
# function to handle an opening tag in the doc
# this will be called when the closing ">" of the tag is reached
def handle_starttag(self, tag, attrs):
global paragraphs
if tag == "p":
paragraphs += 1
print ("Encountered a start tag:", tag)
pos = self.getpos() # returns a tuple indication line and character
print ("\tAt line: ", pos[0], " position ", pos[1])
if attrs.__len__() > 0:
print ("\tAttributes:")
for a in attrs:
print ("\t", a[0],"=",a[1])
# function to handle character and text data (tag contents)
def handle_data(self, data):
if (data.isspace()):
return
print ("Encountered some text data:", data)
pos = self.getpos()
print ("\tAt line: ", pos[0], " position ", pos[1])
# function to handle the processing of HTML comments
def handle_comment(self, data):
print ("Encountered comment:", data)
pos = self.getpos()
print ("\tAt line: ", pos[0], " position ", pos[1])
def main():
# instantiate the parser and feed it some HTML
parser = MyHTMLParser()
# open the sample HTML file and read it
f = open("samplehtml.html")
if f.mode == "r":
contents = f.read() # read the entire file
parser.feed(contents)
print ("Paragraph tags:", paragraphs)
if __name__ == "__main__":
main()