加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python响应解码

发布时间:2020-12-20 13:33:33 所属栏目:Python 来源:网络整理
导读:对于使用urllib的以下行: # some request object existsresponse = urllib.request.urlopen(request)html = response.read().decode("utf8") read()返回什么格式的字符串?我一直试图从Python的文档中找到它,但它根本没有提到它.为什么要解码?解码是否将对
对于使用urllib的以下行:

# some request object exists
response = urllib.request.urlopen(request)
html = response.read().decode("utf8")

read()返回什么格式的字符串?我一直试图从Python的文档中找到它,但它根本没有提到它.为什么要解码?解码是否将对象解码为utf-8或utf-8?从什么格式到它将它解码为什么格式?解码文档也没有提到这一点.是Python的文档是那么可怕,还是我不理解某些标准约定?

我想将该HTML存储在UTF-8文件中.我会做一个常规的写作,还是我需要“编码”回某些东西然后写出来?

注意:我知道urllib已被弃用,但我现在无法切换到urllib2

解决方法

问python:

>>> r=urllib.urlopen("http://google.com")
>>> a=r.read()
>>> type(a)
0: <type 'str'>
>>> help(a.decode)
Help on built-in function decode:

decode(...)
    S.decode([encoding[,errors]]) -> object

    Decodes S using the codec registered for encoding. encoding defaults
    to the default encoding. errors may be given to set a different error
    handling scheme. Default is 'strict' meaning that encoding errors raise
    a UnicodeDecodeError. Other possible values are 'ignore' and 'replace'
    as well as any other name registered with codecs.register_error that is
    able to handle UnicodeDecodeErrors.

>>> b = a.decode('utf8')
>>> type(b)
1: <type 'unicode'>
>>>

所以,似乎read()返回一个str. .decode()从UTF-8解码为Python的内部unicode格式.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读