2

我正在尝试使用 HTMLParser 从 HTML 页面中读取标题标签。但是我收到了上述错误。我的课看起来像这样:

读标题.py

from HTMLParser import HTMLParser
import urllib


class MyHTMLParser(HTMLParser):
    def __init__(self, url):
        HTMLParser.__init__(self)        
        self.url = url
        self.data = urllib.urlopen(url).read() 
        self.feed(self.data)
        self.intitle = ""
        self.mytitle = ""

    def handle_starttag(self, tag, attrs):
        self.intitle = tag == "title"

    def handle_data(self, data): 
        if self.intitle:
            self.mytitle = data
            return self.mytitle

我使用以下命令运行代码并得到错误:

import urllib
import readtitle
parser = readtitle.MyHTMLParser("http://docs.python.org/tutorial/classes.html")

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "readtitle.py", line 10, in __init__
 self.feed(self.data)
File "/usr/lib/python2.6/HTMLParser.py", line 108, in feed
 self.goahead(0)
File "/usr/lib/python2.6/HTMLParser.py", line 142, in goahead
 if i < j: self.handle_data(rawdata[i:j])
File "readtitle.py", line 18, in handle_data
if self.intitle:
AttributeError: MyHTMLParser instance has no attribute 'intitle'
4

1 回答 1

2

在运行之前运行self.feed(),然后调用handle_data()(根据跟踪判断)self.intitle = ""
使固定:

  self.url = url
  self.data = urllib.urlopen(url).read() # Perhaps there should be a decode() here?
  self.intitle = False
  self.mytitle = "" 
  self.feed(self.data)

--------------------------------------

调试始终是最重要的部分。运行此代码并查看它打印的内容。

from HTMLParser import HTMLParser
import urllib, sys

class MyHTMLParser(HTMLParser):
  def __init__(self, url):
    HTMLParser.__init__(self)        
    self.url = url
    self.data = urllib.urlopen(url).read()
    self.in_title = False
    self.title = ''
    self.feed(self.data)
  def handle_starttag(self, tag, attrs):
    if tag == 'body': sys.exit('Found <body>, quitting') # Much easier to look at
    self.in_title = (tag == 'title')
    print 'Handled start of', tag, '  in_title is', self.in_title
  def handle_endtag(self, tag):
    print 'Handled end of', tag
  def handle_data(self, data):
    print "Handling data:", repr(data)
    if self.in_title:
        print "Apparently, we are in a <title> tag. self.title is now", repr(data)
        self.title = data
        print data
        return self.title

parser = MyHTMLParser("http://www.york.ac.uk/teaching/cws/wws/webpage1.html")

为方便起见,相关页面的 HTML:

<HMTL>
<HEAD>
<TITLE>webpage1</TITLE>
</HEAD>
<BODY BGCOLOR="FFFFFf" LINK="006666" ALINK="8B4513" VLINK="006666">
于 2012-07-10T09:11:03.860 回答