我正在使用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中存在的特殊字符。如何编码/解码文本而不丢失任何数据?
答案 0 :(得分: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.....
多田!
答案 1 :(得分:0)
所以看起来页面已损坏。它指定了UTF-8编码,但在该编码中无效。
urlopen(...).read()
返回一个字节字符串(str
)。当您将其提供给lxml
时,它会尝试使用UTF-8对其进行解码并失败。
这可能不是最好的方法,但我们可以手动指定不同的编码,例如Latin-1:
response = urllib.urlopen(...).read().decode('latin-1')
现在response
是一个文本字符串(unicode
),这就是LXML想要使用的内容。