【问题标题】:urllib.request.urlopen return bytes, but I cannot decode it [duplicate]urllib.request.urlopen 返回字节,但我无法解码它[重复]
【发布时间】:2016-05-09 09:56:31
【问题描述】:

我尝试使用urllib.request 的urlopen() 方法解析网页,例如:

from urllib.request import Request, urlopen
req = Request(url)
html = urlopen(req).read()

但是,最后一行以字节为单位返回了结果。

所以我尝试对其进行解码,例如:

html = urlopen(req).read().decode("utf-8")

但是发生了错误:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte.

通过一些研究,我找到了one related answer,它解析charset 来决定解码。但是,该页面没有返回字符集,当我尝试在 Chrome Web Inspector 上检查它时,在其标题中写入了以下行:

<meta charset="utf-8">

那么为什么我不能用utf-8 解码呢?以及如何成功解析网页?

网址是http://www.vogue.com/fashion-shows/fall-2016-menswear/fendi/slideshow/collection#2,我想把图片保存到我的磁盘。

请注意,我使用的是 Python 3.5.1。我还注意到我上面写的所有工作在我的其他抓取程序中运行良好。

【问题讨论】:

    标签: python python-3.x decode urllib urlopen


    【解决方案1】:

    内容用gzip压缩。你需要解压:

    import gzip
    from urllib.request import Request, urlopen
    
    req = Request(url)
    html = gzip.decompress(urlopen(req).read()).decode('utf-8')
    

    如果你使用requests,它会自动为你解压:

    import requests
    html = requests.get(url).text  # => str, not bytes
    

    【讨论】:

    • 谢谢。你能分享一下如何知道它是 gzip 吗?
    • @Blaszard 副本有这个
    • @Blaszard, urlopen(req).info()['content-encoding']
    猜你喜欢
    • 2015-10-20
    • 1970-01-01
    • 2018-03-08
    • 2016-11-03
    • 2016-07-10
    • 2017-09-02
    • 2013-12-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多