2

我正在使用 Python & lxml 并遇到错误

我的代码

>>>import urllib
>>>from lxml import html

>>>response = urllib.urlopen('http://www.edmunds.com/dealerships/Texas/Grapevine/GrapevineFordLincoln_1/fullservice-505318162.html').read()
>>>dom = html.fromstring(response)

>>>dom.xpath("//div[@class='description item vcard']")[0].xpath(".//p[@class='service-review-paragraph loose-spacing']")[0].text_content()

追溯

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/lxml/html/__init__.py", line 249, in text_content
return _collect_string_content(self)
File "xpath.pxi", line 466, in lxml.etree.XPath.__call__ (src/lxml/lxml.etree.c:119105)
File "xpath.pxi", line 242, in lxml.etree._XPathEvaluatorBase._handle_result (src/lxml/lxml.etree.c:116936)
File "extensions.pxi", line 552, in lxml.etree._unwrapXPathObject (src/lxml/lxml.etree.c:112473)
File "apihelpers.pxi", line 1344, in lxml.etree.funicode (src/lxml/lxml.etree.c:21864)
UnicodeDecodeError: 'utf8' codec can't decode byte 0x93 in position 477: invalid start byte

问题是我正在获取的 div 中存在的特殊字符。如何在不丢失任何数据的情况下对文本进行编码/解码?

4

2 回答 2

5

解析器假定这是一个 utf-8 文件,但事实并非如此。最简单的做法是先将其转换为 unicode,通过了解页面的编码

>>> url =  urllib.urlopen('http://www.edmunds.com/dealerships/Texas/Grapevine/GrapevineFordLincoln_1/fullservice-505318162.html')
>>> url.headers.get('content-type')
'text/html; charset=ISO-8859-1'

>>> response = url.read()
#let's convert to unicode first
>>> response_unicode = codecs.decode(response, 'ISO-8859-1')
>>> dom = html.fromstring(response_unicode)
#and now...
>>> dom.xpath("//div[@class='description item vcard']")[0].xpath(".//p[@class='service-review-paragraph loose-spacing']")[0].text_content()
u'\n                  On December 5th, my vehicle completely shut down.\nI had it towed to Grapevine Ford where they told me that the intak.....

多田!

于 2012-04-19T11:02:45.477 回答
0

所以看起来页面已损坏。它指定了 UTF-8 编码,但在该编码中无效。

urlopen(...).read()返回一个字节串 ( str)。当您将其提供给 时lxml,它会尝试使用 UTF-8 对其进行解码并失败。

这可能不是最好的方法,但我们可以手动指定不同的编码,例如 Latin-1:

response = urllib.urlopen(...).read() .decode(' latin-1 ')

现在response是一个文本字符串 ( unicode),这正是 LXML 想要处理的。

于 2012-04-19T10:55:54.613 回答