程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

在Python中将Unicode转换为ASCII而没有错误

发布于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年更新:

截至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压缩文件可以再次读入字节并最终解码为正常的可读文本。

2010年的原始答案:

我们能获得用于的实际价值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黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

13 0
收藏该文
已收藏

评论内容:(最多支持255个字符)