【发布时间】:2015-11-12 16:10:16
【问题描述】:
我正在使用 python 2.7.X。我加载了一些 XML,XML 是 utf-8 编码的。所以我做了以下事情:
def get_xml(self):
r = requests.get("https://dataserver.com")
xml = r.text
return xml.encode("utf-8")
def parse_xml(xml):
tree = ET.fromstring(xml)
for child in tree:
print " Raw type = " + str(type(child.attrib["name"]))
print "Encoded type = " + str(type(child.attrib["name"].encode("utf-8")))
print child.attrib["name"].encode("utf-8")
print str(child.attrib["name"])
print "------------"
这会导致以下错误:
Raw type = <type 'unicode'>
Encoded type = <type 'str'>
Malmö FF - Paris SG
Traceback (most recent call last):
...
UnicodeEncodeError: 'ascii' codec can't encode characters in position 4-5: ordinal not in range(128)
所以,UnicodeEncodeError 对我来说很清楚。但是,在将unicodestring 编码为utf-8string 之后,我希望它能够正确表示。也就是说,Malmö FF 实际上应该是Malmö FF。
我在这里做错了什么?
【问题讨论】: