我已经搜索了该网站,但没有找到适合我的答案。我的问题是我正在尝试将 xml 写入文件,当我从终端运行脚本时,我得到:
Traceback (most recent call last):
File "fetchWiki.py", line 145, in <module>
pageDictionary = qSQL(users_database)
File "fetchWiki.py", line 107, in qSQL
writeXML(listNS)
File "fetchWiki.py", line 139, in writeXML
f1.write(doc.toprettyxml(indent="\t", encoding="utf-8"))
File "/usr/lib/python2.7/xml/dom/minidom.py", line 57, in toprettyxml
self.writexml(writer, "", indent, newl, encoding)
File "/usr/lib/python2.7/xml/dom/minidom.py", line 1751, in writexml
node.writexml(writer, indent, addindent, newl)
----//---- more lines in here ----//----
self.childNodes[0].writexml(writer, '', '', '')
File "/usr/lib/python2.7/xml/dom/minidom.py", line 1040, in writexml
_write_data(writer, "%s%s%s" % (indent, self.data, newl))
File "/usr/lib/python2.7/xml/dom/minidom.py", line 297, in _write_data
writer.write(data)
File "/usr/lib/python2.7/codecs.py", line 351, in write
data, consumed = self.encode(object, self.errors)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 1176: ordinal not
in range(128)
这来自以下代码:
doc = Document()
base = doc.createElement('Wiki')
doc.appendChild(base)
for ns_dict in listNamespaces:
namespace = doc.createElement('Namespace')
base.appendChild(namespace)
namespace.setAttribute('NS', ns_dict)
for title in listNamespaces[ns_dict]:
page = doc.createElement('Page')
try:
title.encode('utf8')
page.setAttribute('Title', title)
except:
newTitle = title.decode('latin1', 'ignore')
newTitle.encode('utf8', 'ignore')
page.setAttribute('Title', newTitle)
namespace.appendChild(page)
text = doc.createElement('Content')
text_content = doc.createTextNode(listNamespaces[ns_dict][title])
text.appendChild(text_content)
page.appendChild(text)
f1 = open('pageText.xml', 'w')
f1.write(doc.toprettyxml(indent="\t", encoding="utf-8"))
f1.close()
无论有无编码/解码“igonore”参数,都会发生错误。添加
# -*- coding: utf-8 -*-
没有帮助。
我使用 Eclipse 和 Pydoc 创建了 python 文档,它可以正常工作,没有问题,但是当我从终端运行它时,它会出错。
非常感谢任何帮助,包括我没有找到的答案的链接。
谢谢。