Python:给定一个链接,如果链接是图像,如何在本地保存,如果不是图像,如何不保存?

2024-10-01 02:18:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在使用

import urllib

urllib.urlretrieve("http://www.digimouth.com/news/media/2011/09/google-logo.jpg", "local-filename.jpg")

有没有办法看看链接是否包含图片,如果没有那么就不需要下载,如果有,那么就下载。你知道吗

谢谢!你知道吗


Tags: importcomhttplocalwwwgoogleurllibfilename
1条回答
网友
1楼 · 发布于 2024-10-01 02:18:20

扩展名并不意味着文件是实际图像,如果要检查文件是否确实是图像,可以使用imagemagik identify

from subprocess import check_output, CalledProcessError
from tempfile import NamedTemporaryFile
import requests
from shutil import move

r = requests.get("http://www.digimouth.com/news/media/2011/09/google-logo.jpg").content
tmp = NamedTemporaryFile("wb", delete=False, dir=".")
tmp.write(r)


try:    
    out = check_output(["identify", "-format", "%m", tmp.name])
    print(out)
    move(tmp.name, "whatever.{}".format(out.lower()))
except CalledProcessError:
    tmp.delete = True

要查看所有支持的格式,请运行identify -list format。你知道吗

相关问题 更多 >