Python HTMLParser:AttributeError

时间:2017-06-15 11:00:43

标签: python python-2.7 html-parsing

我正在使用HTMLParser(python 2.7)解析我用urllib2下拉的页面,当我想将数据存储到 feed 方法的列表中时,我遇到了AttributeError异常。但是如果注释掉 __ init __ 方法,则异常消失了

main.py

# -*- coding: utf-8 -*-
from HTMLParser import HTMLParser
import urllib2
import sys
reload(sys)
sys.setdefaultencoding('utf-8')


class MyHTMLParser(HTMLParser):
    def __init__(self):
        self.terms = []
        self.definitions = []

    def handle_starttag(self, tag, attrs):
        # retrive the terms
        if tag == 'div':
            for attribute, value in attrs:
                if value == 'word':
                    self.terms.append(attrs[1][1])
        # retrive the definitions
                if value == 'desc':
                    if attrs[1][1]:
                        self.definitions.append(attrs[1][1])
                    else:
                        self.definitions.append(None)


parser = MyHTMLParser()
# open page and retrive source page
response = urllib2.urlopen('http://localhost/')
html = response.read().decode('utf-8')
response.close()

# extract the terms and definitions
parser.feed(html)

输出

Traceback (most recent call last):
  File "/Users/megachweng/Project/Anki-Youdao/combined.py", line 35, in <module>
    parser.feed(html)
  File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/HTMLParser.py", line 116, in feed
    self.rawdata = self.rawdata + data
AttributeError: MyHTMLParser instance has no attribute 'rawdata'

2 个答案:

答案 0 :(得分:1)

我认为您没有正确初始化HTMLParser。也许你根本不需要初始化它。这对我有用:

# -*- coding: utf-8 -*-
from HTMLParser import HTMLParser
import urllib2
import sys
reload(sys)
sys.setdefaultencoding('utf-8')


class MyHTMLParser(HTMLParser):  
    def handle_starttag(self, tag, attrs):
        print "Encountered a start tag:", tag
        # retrive the terms
        if tag == 'div':
            for attribute, value in attrs:
                if value == 'word':
                    self.terms.append(attrs[1][1])
        # retrive the definitions
                if value == 'desc':
                    if attrs[1][1]:
                        self.definitions.append(attrs[1][1])
                    else:
                        self.definitions.append(None)


parser = MyHTMLParser()
# open page and retrive source page
response = urllib2.urlopen('http://localhost/')
html = response.read().decode('utf-8')
response.close()

# extract the terms and definitions
parser.feed(html)

<强>更新

# -*- coding: utf-8 -*-
from HTMLParser import HTMLParser
import urllib2
import sys
reload(sys)
sys.setdefaultencoding('utf-8')


class MyHTMLParser(HTMLParser):
    def __init__(self):
        HTMLParser.__init__(self)
        self.terms = []
        self.definitions = []

    def handle_starttag(self, tag, attrs):
        # retrive the terms
        for attribute in attrs:
            if attribute[0] == 'align':
                self.terms.append(attribute[1])
                self.definitions.append(attribute[1])


parser = MyHTMLParser()

html = "<table align='center'><tr><td align='left'><p>ciao</p></td></tr></table>"

# extract the terms and definitions
parser.feed(html)

print parser.terms
print parser.definitions

输出:

[&#39; center&#39;,&#39; left&#39;]

[&#39; center&#39;,&#39; left&#39;]

答案 1 :(得分:0)

好的,我得到了解决方案,super().__init__无法正常工作,必须硬编码名称

def __init__(self):
        HTMLParser.__init__(self)