发布于2019-08-21 21:29 阅读(716) 评论(0) 点赞(13) 收藏(5)
我的代码只是抓取一个网页,然后将其转换为Unicode。
html = urllib.urlopen(link).read()
html.encode("utf8","ignore")
self.response.out.write(html)
但我得到一个UnicodeDecodeError
:
Traceback (most recent call last):
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/webapp/__init__.py", line 507, in __call__
handler.get(*groups)
File "/Users/greg/clounce/main.py", line 55, in get
html.encode("utf8","ignore")
UnicodeDecodeError: 'ascii' codec can't decode byte 0xa0 in position 2818: ordinal not in range(128)
我认为这意味着HTML包含一些在某处错误形成的Unicode尝试。我可以删除导致问题的任何代码字节而不是出错吗?
截至2018年2月,使用压缩gzip
已经变得非常流行(大约73%的网站使用它,包括谷歌,YouTube,雅虎,维基百科,Reddit,Stack Overflow和Stack Exchange网站等大型网站)。
如果你使用gzip响应进行原始答案中的简单解码,你会收到类似或类似的错误:
UnicodeDecodeError:'utf8'编解码器无法解码位置1中的字节0x8b:意外的代码字节
为了解码gzpipped响应,您需要添加以下模块(在Python 3中):
import gzip
import io
注意: 在Python 2中,您将使用StringIO
而不是io
然后你可以像这样解析内容:
response = urlopen("https://example.com/gzipped-ressource")
buffer = io.BytesIO(response.read()) # Use StringIO.StringIO(response.read()) in Python 2
gzipped_file = gzip.GzipFile(fileobj=buffer)
decoded = gzipped_file.read()
content = decoded.decode("utf-8") # Replace utf-8 with the source encoding of your requested resource
此代码读取响应,并将字节放在缓冲区中。然后,gzip
模块使用该GZipFile
函数读取缓冲区。之后,gzip压缩文件可以再次读入字节并最终解码为正常的可读文本。
我们能获得用于的实际价值link
吗?
另外,当我们尝试.encode()
已经编码的字节串时,我们通常会遇到这个问题。所以你可能会尝试先解码它
html = urllib.urlopen(link).read()
unicode_str = html.decode(<source encoding>)
encoded_str = unicode_str.encode("utf8")
举个例子:
html = '\xa0'
encoded_str = html.encode("utf8")
失败了
UnicodeDecodeError: 'ascii' codec can't decode byte 0xa0 in position 0: ordinal not in range(128)
而:
html = '\xa0'
decoded_str = html.decode("windows-1252")
encoded_str = decoded_str.encode("utf8")
成功没有错误。请注意,我使用“windows-1252”作为示例。我从chardet得到了这个,它有0.5信心,它是正确的!(好吧,如1个字符长度的字符串所示,您期望什么)您应该将其更改为从返回的字节字符串的编码.urlopen().read()
到适用于您检索的内容的编码。
我看到的另一个问题是.encode()
string方法返回修改后的字符串,并没有修改源代码。因此self.response.out.write(html)
,html不是来自html.encode的编码字符串(如果这是你最初的目标),那就没用了。
正如Ignacio所建议的那样,检查源网页上的返回字符串的实际编码read()
。它位于Meta标签之一或响应中的ContentType标头中。然后使用它作为参数.decode()
。
但是请注意,不应该假设其他开发人员有足够的责任来确保标头和/或元字符集声明与实际内容匹配。(这是一个PITA,是的,我应该知道,我之前是其中之一)。
作者:黑洞官方问答小能手
链接:https://www.pythonheidong.com/blog/article/51268/c236d91772a5ad1f1ce2/
来源:python黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 python黑洞网 All Rights Reserved 版权所有,并保留所有权利。 京ICP备18063182号-1
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!