这几行python代码。执行有错?
from xml.sax.handler import ContentHandlerfrom xml.sax import parseclass PageMaker(ContentHandler): passthrough = False def startElement(self, name, attrs): if name == 'page': self.passthrough = True self.out = open(attrs[name]+'.html', 'w') self.out.write('<html><head>\n') self.out.write('<title>%s</title>\n' % attrs['title']) self.out.write('</head><body>\n') elif self.passthrough: self.out.write('<' + name) for key, val in attrs.items(): self.out.write('"%s = %s"' %(key, val)) self.out.write('>') def endElement(self, name): if name == 'page': self.passthrough = False self.out.write('\n</body></html>\n') self.out.close() elif self.passthrough: self.out.write('</%s>' % name) def characters(self, chars): if self.passthrough: self.out.write(chars)parse('website.xml', PageMaker())
from xml.sax.handler import ContentHandlerfrom xml.sax import parseimport osclass PageMaker(ContentHandler): passthrough = False #判断是否为新文件 directory = '' #当前目录 def startElement(self, name, attrs): if name == 'page': self.passthrough = True #设置为新文件 self.out = open(self.directory + attrs['name'] + '.html', 'w') #打开或者创建新文件 self.out.write('<html>\n<head>\n') self.out.write('<title>%s</title>\n' % attrs['title']) #设置标题 self.out.write('</head>\n<body>\n') elif name == 'directory': #判断是否为目录 if not os.path.exists(attrs['name']): #判断此目录是否存在 os.mkdir(attrs['name']) #创建目录 self.directory = attrs['name'] + '\\' elif self.passthrough: self.out.write('<' + name) #定义标签 for key, val in attrs.items(): #定义属性 self.out.write(' %s="%s"' % (key, val)) self.out.write('>') def endElement(self, name): if name == 'page': self.passthrough = False #文件结束 self.out.write('\n</body>\n</html>') self.out.close() elif self.passthrough: #设置关闭标签 self.out.write('</%s>' % name) def characters(self, chars): #输出文本内容 if self.passthrough : self.out.write(chars)parse('website.xml', PageMaker())