我似乎無法添加訪問HTMLParser中的任何新變量。我正在追蹤我見過的例子here。我在__init__裏面添加一個變量沒有任何錯誤,但是當我嘗試在一個方法中訪問它時,我被告知它不存在。無法訪問HTMLParser中的新變量
#!/usr/bin/env python
from HTMLParser import HTMLParser
import urllib
class parse(HTMLParser):
def __init__(self, data):
HTMLParser.__init__(self)
self.feed(data)
self.foo = 'err'
def handle_starttag(self, tag, attrs):
print self.foo
if tag == 'a':
for attr, value in attrs:
if attr == 'href':
print value[10:]
continue
def handle_data(self, text):
pass
def handle_endtag(self, tag):
pass
page = urllib.urlopen('http://docs.python.org/library/htmlparser.html').read()
p = parse(page)
這裏的輸出:
Traceback (most recent call last):
File "./doit.py", line 34, in <module>
p = parse(page)
File "./doit.py", line 9, in __init__
self.feed(data)
File "/usr/lib/python2.6/HTMLParser.py", line 108, in feed
self.goahead(0)
File "/usr/lib/python2.6/HTMLParser.py", line 148, in goahead
k = self.parse_starttag(i)
File "/usr/lib/python2.6/HTMLParser.py", line 271, in parse_starttag
self.handle_starttag(tag, attrs)
File "./doit.py", line 14, in handle_starttag
print self.foo
AttributeError: parse instance has no attribute 'foo'
感謝您的幫助