0

我需要从模板创建一些文件。我正在使用 psycopg2 从数据库中获取数据。然后我循环通过。现在我需要写入文件。谢谢!

import sys
from HTMLParser import HTMLParser
from xml.etree import cElementTree as etree
import psycopg2
import psycopg2.extras

class LinksParser(HTMLParser):
  def __init__(self):
      HTMLParser.__init__(self)
      self.tb = etree.TreeBuilder()

  def handle_starttag(self, tag, attributes):
      self.tb.start(tag, dict(attributes))

  def handle_endtag(self, tag):
      self.tb.end(tag)

  def handle_data(self, data):
      self.tb.data(data)

  def close(self):
      HTMLParser.close(self)
      return self.tb.close()

conn = psycopg2.connect(dbname="**", user="**", password="**", host="/tmp/", port="**")
cur.execute("SELECT * FROM landingpagedata;")
rows = cur.fetchall()
template = 'template.html'

parser = LinksParser()
# parser.feed(open('landingIndex.html').read()) #for testing
# root = parser.close()

for row in rows:
    parser.feed(open(template).read())
    root = parser.close()

    #title
    title = root.find(".//title")
    title.text = str(row['title'])
    f = open(row['page_name'], 'w')
    root.write(f)
    parser = LinksParser()

错误是:

Traceback (most recent call last):
File "/Users/Morgan13/Programming/LandingPageBuilder/landingPages/landingBuilderTest.py", line 87, in <module>
    main()
File "/Users/Morgan13/Programming/LandingPageBuilder/landingPages/landingBuilderTest.py", line 75, in main
    root.write('page_name')
AttributeError: write

哦,我正在使用 open('page', 'w') 因为这些页面已经存在?

4

1 回答 1

1

我想你想要f.write(root),不是root.write(f)。(假设 str(root) 为您提供了您想要写出的 HTML。)

于 2013-05-09T02:03:45.453 回答