+ -
当前位置:首页 → 问答吧 → 帮忙调试一个python小程序

帮忙调试一个python小程序

时间:2011-03-22

来源:互联网

是网上看到的一程序,功能是为HTML文档中的属性值添加引号。
python的版本是2.5,然而我运行报错,我改了self.pieces.append("" % (tag))这句也得不到理想的效果,请帮我调试下,3q。


Python code

import HTMLParser
import urllib
import sys

#定义HTML解析器
class parseAttrs(HTMLParser.HTMLParser):
    def init_parser(self):
        self.pieces = []
    def handle_starttag(self, tag, attrs):
        fixedAttrs = ""
        for name, value in attrs:
            fixedAttrs += "%s=\"%s\" " % (name, value)
            self.pieces.append("<%s %s>" % (tag, fixedAttrs))
    def handle_charref(self, name):
        self.pieces.append("&#%s;" % (name))
    def handle_endtag(self, tag):
        self.pieces.append("" % (tag))
    def handle_entityref(self, ref):
        self.pieces.append("&%s" % (ref))
    def handle_data(self, text):
        self.pieces.append(text)
    def handle_comment(self, text):
        self.pieces.append("" % (text))
    def handle_pi(self, text):
        self.pieces.append("" % (text))
    def handle_decl(self, text):
        self.pieces.append("" % (text))
    def parsed(self):
        return "".join(self.pieces)

#创建HTML解析器的实例
attrParser = parseAttrs()

#初始化解析器数据
attrParser.init_parser()

#把HTML文件传给解析器
attrParser.feed(urllib.urlopen("test2.html").read())

#显示原来的文件内容
print "原来的文件\n========================"
print open("test2.html").read()

#显示解析后的文件
print "解析后的文件\n========================"
print attrParser.parsed()

attrParser.close() 




其中test2.html的代码是:
HTML code

<html>
<head>
<meta content="text/html; charset=utf-8"
http-equiv="content-type"/>
<title>Web页面</title>
</head>
<body>
<H1>Web页面清单</H1>
<a href=http://www.python.org>Python网站</a>
<a href=test.html>本地页面</a>
<img SRC=test.jpg>
</body>
</html>


作者: Handsome_Engineer   发布时间: 2011-03-22

学会阅读出错信息。真的看过出错信息,并且看不明白,请把出错信息贴出来让别人帮忙看。不然就是浪费大家时间了。

作者: iambic   发布时间: 2011-03-22