【发布时间】:2015-08-25 10:59:52
【问题描述】:
我从 Schema.org 获得一个 URL。它是 content-type="text/html"
有时,read() 会按预期运行 b' ....'
有时,read() 会返回其他内容 b'\x1f\x8b\x08\x00\x00\x00\x00 ...'
try:
with urlopen("http://schema.org/docs/releases.html") as f:
txt = f.read()
except URLError:
return
我尝试使用txt = f.read().decode("utf-8").encode() 解决此问题,但这会导致错误...有时:UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte
显而易见的解决方法是测试第一个字节是否为十六进制并相应地处理。
我的问题是:这是一个错误还是其他什么?
编辑 相关question。显然,有时我会得到一个 gzipped 流。
最后 我通过将以下代码添加为proposed here
解决了这个问题if 31 == txt[0]:
txt = decompress(txt, 16+MAX_WBITS)
问题仍然存在;为什么这有时会返回 text/html 而有时会被压缩?
【问题讨论】:
-
我只能重现您收到 b'.. 在我看来,您收到的其他回复与您的互联网连接以某种方式失败有关。跨度>
-
@SlashV 我可能每 5 次收到一次
-
我运行代码 200 次...
-
@SlashV 我正在使用 PyCharm,我不知道
-
@SlashV 添加截图
标签: python-3.x urlopen