python - 如何在不丢失任何数据的情况下处理 UnicodeDecodeError?

标签 python web-scraping lxml

我正在使用 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 中的特殊字符。如何在不丢失任何数据的情况下对文本进行编码/解码?

最佳答案

解析器假设这是一个 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.....

多田!

关于python - 如何在不丢失任何数据的情况下处理 UnicodeDecodeError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10226342/

相关文章:

python - 在康威的生命游戏中计算活着的邻居不起作用

python - 有没有办法在 Python 的多重继承对象中访问重写的方法?

Python - 如何连接列表中由特定值分隔的元素

python - 从滚动时添加新表格的页面中抓取 HTML 数据

python - 使用 lxml,是什么导致 "lxml.etree.XMLSyntaxError: Document is empty"错误?

python - 将 groupby 与多个索引列或索引一起使用时

python - 抓取YouTube channel 的前一天视频-bs4

Ruby:如何将多线程合并到这个网络抓取场景中?

python - 在我的网页抓取程序中提取第一个和最后一个页码时如何修复 "List index out of range"错误?

python lxml inkscape 命名空间标签