【问题标题】:Python request only a certain number of bytesPython只请求一定数量的字节
【发布时间】:2021-12-23 16:06:39
【问题描述】:
我正在从 URL 请求 GIF 文件,并且我试图通过仅读取第一帧的字节来避免下载整个文件。有没有办法使用 requests 或 urllib.request 模块,只允许您请求/下载一定数量的字节?
import requests
r = requests.get("https://cdn.discordapp.com/attachments/712243005519560736/908229068909068318/sample_1.gif")
【问题讨论】:
标签:
python
python-requests
byte
gif
【解决方案1】:
你可以尝试先打开图片使用img.n_frames它
from io import BytesIO
from PIL import Image
img = Image.open(BytesIO(r.content))
img.n_frames
输出
1
【解决方案2】:
您可以使用requests.Response.iter_content 来迭代响应数据。
读取前 10 个字节以提取宽度和
GIF 图片的高度:
测试:
import struct
import requests
URL = "https://cdn.discordapp.com/attachments/712243005519560736/908229068909068318/sample_1.gif"
def main():
with requests.get(URL, stream=True) as r:
header = next(r.iter_content(chunk_size=10))
typ, version, width, height = struct.unpack("<3s3sHH", header)
print(typ, version, width, height)
if __name__ == "__main__":
main()
测试:
$ python test.py
b'GIF' b'89a' 10 10
使用这种方法,您当然需要知道字节偏移量
和您要阅读的框架的大小。