【发布时间】: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