python - 使用 lxml tostring() 获取原始字符串

标签 python python-3.x lxml

我正在使用 lxml,我正在尝试获取原始的 xml 字符串:

>>> elem = etree.fromstring("<tag>áéíóúñü</tag>")
>>> etree.tostring(elem)
b'<tag>&#225;&#233;&#237;&#243;&#250;&#241;&#252;</tag>'

我发现获取原始字符串的唯一方法是:

>>> etree.tostring(elem, encoding = "utf-8").decode("utf-8")
'<tag>áéíóúñü</tag>'

有没有更好的方法?

最佳答案

这个怎么样:

In [31]: elem = etree.fromstring("<tag>❄</tag>")

In [32]: etree.tostring(elem, encoding=str)
Out[32]: '<tag>❄</tag>'

关于python - 使用 lxml tostring() 获取原始字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43770156/

相关文章:

python - 如何使用 beautifulsoup 在嵌套的 div 中获取文本

python - 为什么这在 c 中有效但在 python 中无效 : (a = 5) == 5

python - 使用 BeautifulSoup 提取 HTML 注释之间的文本

Python - 解析 HTML 类

python - 当我使用整数作为属性值时,为什么 LXML ElementMaker 会中断?

python - 使用列表而不是 numpy 数组

python - Keras fit_generator() 与扩展序列的生成器返回的样本数多于总数

python - 附加到字典中的列表

python - Python 中的 ICMP pinger 应用程序 - 错误 : operation not permitted?

python-3.x - 创建 os.DirEntry