2

HTMLParserを使用してHTMLページからタイトルタグを読み取ろうとしています。ただし、上記のエラーが発生します。私のクラスは次のようになります。

readtitle.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 に答える