gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 22:03:00 33 4
gpt4 key购买 nike

我正在使用 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/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com