【问题标题】:urllib for python 3python 3的urllib
【发布时间】:2016-02-14 19:17:57
【问题描述】:

python3中这段代码有问题:

import urllib.request
fhand=urllib.request.urlopen('http://www.py4inf.com/code/romeo.txt')
print(fhand.read())

它的输出是:

b'But soft what light through yonder window breaks'
b'It is the east and Juliet is the sun'
b'Arise fair sun and kill the envious moon'
b'Who is already sick and pale with grief'

为什么我得到b'...'? 我该怎么做才能得到正确的回应?

正确的文字应该是

But soft what light through yonder window breaks
It is the east and Juliet is the sun
Arise fair sun and kill the envious moon
Who is already sick and pale with grief

【问题讨论】:

标签: python python-3.x urllib


【解决方案1】:

b'...'byte string:一个字节数组,而不是真正的字符串。

convert to a real string,使用

fhand.read().decode()

这使用默认编码“UTF-8”。对于 ASCII 编码,使用

fhand.read().decode("ASCII")

例如

【讨论】:

  • 还有更简单的方法吗? 'fhand.read().decode("ASCII")' OMG 好长啊!
  • @Fourier: decode() 有合理的默认值。只需留下“ASCII”即可。够短吗?
  • @Fourier:感谢您询问较短的表格。
  • 感谢您的耐心!
【解决方案2】:

正如the documentation 所说,urlopen 返回一个对象,其read 方法为您提供字节序列,而不是字符序列。为了将字节转换为您想要的可打印字符,您需要应用 decode 方法,使用字节所在的编码。

结果 似乎 有意义的原因是 Python 选择用于显示字节的默认编码恰好是正确的编码,或者至少恰好与这些字符的正确编码匹配。

要正确执行此操作,您应该read().decode(encoding) 其中encoding 是来自Content-Type HTTP 标头的编码值,可通过HTTPResponse object 访问(即fhand,在您的代码中)。如果没有Content-Type 标头,或者如果它没有指定编码,则您将被简化为guessing which encoding to use,但对于典型的英文文本并不重要,在许多其他情况下它可能会是UTF -8.

【讨论】:

    【解决方案3】:

    Python 3 区分字节序列和字符串。字符串前面的“b”告诉您 urllib 将内容作为“原始”字节返回。可能值得一读 python 3 字节/字符串的情况,但基本上,你确实得到了正确的文本。如果您不希望结果为字节,则只需将其转换回“真正的”python 字符串。

    【讨论】:

      【解决方案4】:

      第三方 requests 库自动处理解码为 un​​icode 字符串。它会尽力推断正确的编码,因此您无需自己猜测编码。

      >>> import requests
      >>> r = requests.get('http://www.py4inf.com/code/romeo.txt')
      >>> print(r.text)
      But soft what light through yonder window breaks
      It is the east and Juliet is the sun
      Arise fair sun and kill the envious moon
      Who is already sick and pale with grief
      

      urllib.request 和假定的UTF-8 编码相同:

      >>> from urllib.request import urlopen
      >>> r = urlopen('http://www.py4inf.com/code/romeo.txt')
      >>> print(r.read().decode('UTF-8'))
      But soft what light through yonder window breaks
      It is the east and Juliet is the sun
      Arise fair sun and kill the envious moon
      Who is already sick and pale with grief
      

      【讨论】:

        猜你喜欢
        • 2012-09-25
        • 2011-08-16
        • 2011-03-08
        • 1970-01-01
        • 2019-07-21
        • 2015-10-16
        • 1970-01-01
        • 1970-01-01
        • 2016-07-28
        相关资源
        最近更新 更多