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

发布于 2021-02-02 23:12:16

我的代码只是刮取一个网页,然后将其转换为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尝试。我能丢掉导致问题的任何代码字节而不出错吗?

关注者
0
被浏览
75
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    使用类似的压缩gzip已变得非常流行(约73%的网站都在使用它,包括Google,YouTube,Yahoo,Wikipedia,Reddit,Stack OverflowStack Exchange Network网站等大型网站)。
    如果你像原始答案中那样使用gzip压缩响应进行简单解码,则会收到类似以下错误:

    UnicodeDecodeError:'utf8'编解码器无法解码位置1的字节0x8b

    为了解码gzpipped响应,你需要添加以下模块(在Python 3中):

    import gzip
    import io
    


  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    然后,你可以像这样解析内容:

    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函数读取缓冲区。之后,可以将压缩后的文件再次读取为字节,最后将其解码为通常可读的文本。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看