4
我想我下面的正確方法,但我仍然得到一個編碼錯誤:XML編碼錯誤,同時以書面形式到文件
from xml.dom.minidom import Document
import codecs
doc = Document()
wml = doc.createElement("wml")
doc.appendChild(wml)
property = doc.createElement("property")
wml.appendChild(property)
descriptionNode = doc.createElement("description")
property.appendChild(descriptionNode)
descriptionText = doc.createTextNode(description.decode('ISO-8859-1'))
descriptionNode.appendChild(descriptionText)
file = codecs.open('contentFinal.xml', 'w', encoding='ISO-8859-1')
file.write(doc.toprettyxml())
file.close()
描述節點包含在ISO-8859-1 encoding
一些字符,這是編碼由指定該網站它自身在元標記。但是,當doc.toprettyxml()
開始在文件中寫入我有以下錯誤:
Traceback (most recent call last):
File "main.py", line 467, in <module>
file.write(doc.toprettyxml())
File "C:\Python27\lib\xml\dom\minidom.py", line 60, in toprettyxml
return writer.getvalue()
File "C:\Python27\lib\StringIO.py", line 271, in getvalue
self.buf += ''.join(self.buflist)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe1 in position 10: ordinal not in range(128)
爲什麼會出現這個錯誤,因爲我解碼,並與相同的標準編碼?
編輯
我在腳本文件下面減速:
#!/usr/bin/python
# -*- coding: utf-8 -*-
可能這是矛盾的?
我不認爲Python聲明是問題。你可以發表描述的內容嗎? – dfb
可以說,如果我們在內容中包含「Orientación」這個詞,我們就會遇到錯誤。該網站是'espanol語言'。在寫入文件之前,不知道內容是否失敗。如果我根本沒有使用編碼,那麼它寫入文件,但不被瀏覽器接受,他們總是說'錯誤行blah列blah' –
聽起來像你的'描述'對象是一個字節串而不是字符串。 – wberry