Tôi đang cố gắng để phân tích, thao tác và đầu ra HTML sử dụng Python của ElementTree:Python ElementTree sẽ không chuyển đổi không bị phá hủy không gian khi sử dụng UTF-8 cho đầu ra
import sys
from cStringIO import StringIO
from xml.etree import ElementTree as ET
from htmlentitydefs import entitydefs
source = StringIO("""<html>
<body>
<p>Less than <</p>
<p>Non-breaking space </p>
</body>
</html>""")
parser = ET.XMLParser()
parser.parser.UseForeignDTD(True)
parser.entity.update(entitydefs)
etree = ET.ElementTree()
tree = etree.parse(source, parser=parser)
for p in tree.findall('.//p'):
print ET.tostring(p, encoding='UTF-8')
Khi tôi chạy này sử dụng Python 2.7 trên Mac OS X 10.6, tôi nhận được:
<p>Less than <</p>
Traceback (most recent call last):
File "bar.py", line 20, in <module>
print ET.tostring(p, encoding='utf-8')
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/etree/ElementTree.py", line 1120, in tostring
ElementTree(element).write(file, encoding, method=method)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/etree/ElementTree.py", line 815, in write
serialize(write, self._root, encoding, qnames, namespaces)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/etree/ElementTree.py", line 931, in _serialize_xml
write(_escape_cdata(text, encoding))
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/etree/ElementTree.py", line 1067, in _escape_cdata
return text.encode(encoding, "xmlcharrefreplace")
UnicodeDecodeError: 'ascii' codec can't decode byte 0xa0 in position 19: ordinal not in range(128)
tôi nghĩ rằng việc xác định "encoding = 'UTF-8'" sẽ chăm sóc của các nhân vật không gian không bị phá hủy, nhưng dường như nó không. Tôi nên làm gì?
Vấn đề không phải là trên đầu vào: thủ thuật UseForeignDTD hoạt động tốt cho điều đó. Vấn đề là trên đầu ra: văn bản trong bộ nhớ chứa 0xA0, mà tôi mong đợi sẽ được chuyển đổi sang biểu diễn UTF-8 của nó bằng ET.tostring (vì tôi đã nói 'encoding = "UTF-8"'). –