1

我正在使用 lxml 和 xpath via 从 html 标签属性中提取文本tag.attrib['title']。我得到:

Málaga Airport

我在浏览器中看到的具有相同 url 的位置:

Málaga Airport

如何将前者转换为后者?

4

1 回答 1

2

似乎 lxml html 解析器假定字节字符串采用“latin1”编码。

因此,除非输入被编码为“latin1”(或“ascii”),否则需要明确指定编码。在这种情况下,它看起来应该是“utf-8”:

>>> from lxml import etree
>>>
>>> html = u"""
... <html>
... <head><title>Test</title></head>
... <body>
... <p test="Málaga">Example</p>
... </body>
... </html>
... """
>>>
>>> html = html.encode('utf-8')
>>>
>>> parser = etree.HTMLParser()
>>> tree = etree.fromstring(html, parser)
>>> print tree.xpath('//p/@test')[0]
Málaga
>>>
>>> parser = etree.HTMLParser(encoding='utf-8')
>>> tree = etree.fromstring(html, parser)
>>> print tree.xpath('//p/@test')[0]
Málaga
于 2012-12-09T01:01:31.943 回答