I am trying to get a value out of a HTML page using the python HTMLParser library. The value I want to get hold of is within this HTML element:
...
<div id="remository">20</div>
...
This is my HTMLParser class so far:
class LinksParser(HTMLParser.HTMLParser):
def __init__(self):
HTMLParser.HTMLParser.__init__(self)
self.seen = {}
def handle_starttag(self, tag, attributes):
if tag != 'div': return
for name, value in attributes:
if name == 'id' and value == 'remository':
#print value
return
def handle_data(self, data):
print data
p = LinksParser()
f = urllib.urlopen("http://example.com/somepage.html")
html = f.read()
p.feed(html)
p.close()
I want the class functionality to get the value 20.
self.recordingcounts the number of nesteddivtags starting from a “triggering” one. When we’re in the sub-tree rooted in a triggering tag, we accumulate the data inself.data.The data at the end of the parse are left in
self.data(a list of strings, possibly empty if no triggering tag was met). Your code from outside the class can access the list directly from the instance at the end of the parse, or you can add appropriate accessor methods for the purpose, depending on what exactly is your goal.The class could be easily made a bit more general by using, in lieu of the constant literal strings seen in the code above,
'div','id', and'remository', instance attributesself.tag,self.attnameandself.attvalue, set by__init__from arguments passed to it — I avoided that cheap generalization step in the code above to avoid obscuring the core points (keep track of a count of nested tags and accumulate data into a list when the recording state is active).