Python AttributeError:XX实例没有属性';intitle&x27;
代码来自: 回溯是:Python AttributeError:XX实例没有属性';intitle&x27;,python,html-parsing,Python,Html Parsing,代码来自: 回溯是: Traceback (most recent call last): File "D:\labs\test.py", line 19, in <module> print titleFinder(html) File "D:\labs\test.py", line 14, in titleFinder parser.feed(html) File "C:\Python27\lib\HTMLParser.py", line 108,
Traceback (most recent call last):
File "D:\labs\test.py", line 19, in <module>
print titleFinder(html)
File "D:\labs\test.py", line 14, in titleFinder
parser.feed(html)
File "C:\Python27\lib\HTMLParser.py", line 108, in feed
self.goahead(0)
File "C:\Python27\lib\HTMLParser.py", line 142, in goahead
if i < j: self.handle_data(rawdata[i:j])
File "D:\labs\test.py", line 10, in handle_data
if self.intitle:
AttributeError: MyHTMLParser instance has no attribute 'intitle'
您的
handle\u data
方法在调用handle\u starttag
之前被调用,此时没有设置intitle
属性
只需将intitle=False
添加到您的类中:
class MyHTMLParser(HTMLParser):
intitle = False
# your methods
handle\u data
是为文档中的所有文本节点调用的,包括空格,因此在报告python中的错误时,在handle\u starttag
之前调用它并不罕见,请包含完整的回溯,这样我们就不必猜测您的错误发生在哪里。添加“intitle=False”后,我仍然收到相同的错误消息。@MattElson:那么请包括完整的回溯。您显示的代码只有一个位置引用了self.intitle
,我的回答应该可以解决这个问题,但完整的回溯可能会显示您忘记的另一个位置。
Traceback (most recent call last):
File "D:\labs\test.py", line 19, in <module>
print titleFinder(html)
File "D:\labs\test.py", line 14, in titleFinder
parser.feed(html)
File "C:\Python27\lib\HTMLParser.py", line 108, in feed
self.goahead(0)
File "C:\Python27\lib\HTMLParser.py", line 142, in goahead
if i < j: self.handle_data(rawdata[i:j])
File "D:\labs\test.py", line 10, in handle_data
if self.intitle:
AttributeError: MyHTMLParser instance has no attribute 'intitle'
from HTMLParser import HTMLParser
import urllib2
def titleFinder(html):
class MyHTMLParser(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
self.title = ''
self.intitle = False #!!!
def handle_starttag(self, tag, attrs):
self.intitle = tag == "title"
def handle_data(self, data):
if self.intitle:
self.title = self.title+data #!!!
parser = MyHTMLParser()
parser.feed(html)
return parser.title
response=urllib2.urlopen("https://stackoverflow.com/questions/13680074/attributeerror-xx-instance-has-no-attribute-intitle")
html= response.read()
print titleFinder(html)
class MyHTMLParser(HTMLParser):
intitle = False
# your methods