urllib.request.urlopen返回字节,但我无法解码它

Bla*_*ard 3 python decode urllib urlopen python-3.x

我尝试使用解析网页urllib.requesturlopen()方法,如:

from urllib.request import Request, urlopen
req = Request(url)
html = urlopen(req).read()
Run Code Online (Sandbox Code Playgroud)

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

所以我尝试解码它,如:

html = urlopen(req).read().decode("utf-8")
Run Code Online (Sandbox Code Playgroud)

但是,发生了错误:

UnicodeDecodeError:'utf-8'编解码器无法解码位置1中的字节0x8b:无效的起始字节.

通过一些研究,我找到了一个相关的答案,解析charset决定解码.但是,该页面不会返回字符集,当我尝试在Chrome Web Inspector上进行检查时,其标题中会写入以下行:

<meta charset="utf-8">
Run Code Online (Sandbox Code Playgroud)

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

网站URL是http://www.vogue.com/fashion-shows/fall-2016-menswear/fendi/slideshow/collection#2,我想将图像保存到我的磁盘.

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

fal*_*tru 8

内容使用压缩gzip.你需要解压缩它:

import gzip
from urllib.request import Request, urlopen

req = Request(url)
html = gzip.decompress(urlopen(req).read()).decode('utf-8')
Run Code Online (Sandbox Code Playgroud)

如果您使用requests,它将自动解压缩:

import requests
html = requests.get(url).text  # => str, not bytes
Run Code Online (Sandbox Code Playgroud)

  • @Blaszard,`urlopen(req).info()['content-encoding']` (3认同)
  • 谢谢。你能分享一下你是如何知道它是gzip的吗? (2认同)