【问题标题】:Python HTMLParser: AttributeErrorPython HTMLParser:属性错误
【发布时间】:2017-11-17 20:19:53
【问题描述】:

我正在使用 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'

【问题讨论】:

  • 对不起,由于某种原因我不能使用任何第三方包

标签: python python-2.7 html-parsing


【解决方案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

输出:

['中心', '左']

['中心', '左']

【讨论】:

  • 是的,它绝对有效,但是任何想法如何将 attrs[1][1] 存储到列表中以便我可以访问它(打印 parser.terms --MyHTMLParser 实例没有属性'条款')
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-21
    • 2013-07-01
    • 2011-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-01
    • 2021-07-24
    相关资源
    最近更新 更多