在xpath中使用unicode作为谓词,使用lxml和python 2.7
问题描述:
我一直在面对的问题是,我有一个带有Unicode字符串的XML文件,需要通过Python-2.7中的lxml来评估它的Xpath。在xpath中使用unicode作为谓词,使用lxml和python 2.7
# -*- coding: utf-8 -*-
from lxml import etree
...
class Language:
description = None
def __init__(self, description):
xpath = "//language[./description = '{}']//description/text()".format(description)
self.description= lang_xml.xpath(xpath)
...
lang = Language(u"Norwegian Bokmål")
给出错误:UnicodeEncodeError: 'ascii' codec can't encode character u'\xe5' in position 14: ordinal not in range(128)
答
停止将它们混合。
xpath = u"//language[./description = '{}']//description/text()".format(description)
确实....谢谢 – unicorn