urllib.request.urlopen返回字节,但是我无法对其进行解码

布拉扎德

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

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

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

所以我尝试将其解码,例如:

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

但是,发生错误:

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

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

<meta charset="utf-8">

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

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

请注意,我使用的是Python 3.5.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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

无法导入urllib.request和urllib.parse

urllib,urllib2,urllib.request.open,AttributeError:“模块”对象没有属性“ urlopen”

模拟urllib.request.urlopen的read函数返回MagicMock签名

urllib.request 的 urlopen 无法在 python 3.7 中打开页面

urllib.request模块无法在我的系统中安装

HTTP错误401:未经授权使用urllib.request.urlopen

HTTPError问题:urllib.request.urlopen python请求错误

带有验证的urllib.request.urlopen(url)

将 urllib.request.urlopen 移动到请求

python:urllib.request.urlopen不起作用

如何处理来自urllib.request.urlopen()的响应编码

替换urllib.request.urlopen(url,ca *)的开启器

Python 3:urllib.request.urlopen和Progressbar

urllib.request.urlopen 不适用于特定网站

无法在urllib.request中使用https代理

Python3:Urllib.request无法正常工作

无法使用 urllib.request 从网站下载文件

urllib.request.urlopen 的行为很奇怪。第二天不返回数据。为什么?

urllib.request.urlopen无法获取堆栈溢出选举的主要页面

我需要使用urllib2.Request / urlopen处理哪些错误/异常?

为什么urllib.request.urlopen在《华尔街日报》的网站上给我404?

Urllib.request和BeautifulSoup

urllib.request.Request说参数无效

Python urllib.request.urlopen:AttributeError:“ bytes”对象没有属性“ data”

Python请求lib工作,urllib.request.urlopen POST不工作

为什么在这种情况下urllib.request.urlopen会阻塞?

python3中来自urllib.request的urlopen的奇怪行为

python3 安全问题,os.system('wget...') 与 urllib.request.urlopen(...)

urllib.request.urlopen(url) 在 python 3 中不起作用