【发布时间】:2011-06-14 21:14:29
【问题描述】:
我似乎无法在 HTMLParser 中添加访问任何新变量。我正在关注我见过的例子here。在 __init__ 中添加变量时我没有收到任何错误,但是当我尝试以一种方法访问它时,我被告知它不存在。
#!/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'
感谢您的帮助
【问题讨论】:
标签: python oop html-parsing