python 通过请求排除不可访问的图像

问题描述 投票:0回答:1

我已经用请求编写了一个非常简单的函数,其中有一个给定的 URL 检查它是否得到响应以及该响应是否是图像。它确实有效,但有时非常慢。我也是 没有经验,不明白为什么会这样。我怎样才能改进它或以更好更快的方式实现同样的事情?

def is_image_url(url):

    try:
        response = requests.get(url)
        status = response.status_code
        print(status)
    
        if response.status_code == 200:
            content_type = response.headers.get('content-type')
            print(content_type)
            if content_type.startswith('image'):
                return True
        return False
    
    except Exception as e:
        print(e)
        return False

我正在使用该功能来排除无法访问的图像,例如来自 Instagram、Facebook 等的图像。 我认为它可以正常工作,因为我实际上只需要检查从 google 自定义搜索 api 获得的 10 张图像。

目前我已经从应用程序中排除了该功能,并尝试通过检查图像高度或宽度来执行类似的操作,以确保它存在并且可以访问,但没有取得太大成功。

python-3.x django image python-requests google-custom-search
1个回答
0
投票
                 for image in img['items']:
                    height = image['image']['height']
                    width = image['image']['width']
                    imgTitle = image['title']
                    imgHtmlTitle = image['htmlTitle']
                    imgContext = image['image']['contextLink']
                    imgLink = image['link']
                    workingImg = is_image_url(imgLink)
                    print(f'alt {height}.... larg {width}')
                    info_img = {'imgTitle' : imgTitle, 'imgHtmlTitle' : imgHtmlTitle, "imgContext" : imgContext, "imgLink" : imgLink}
                    if workingImg:
                       risultati_immagini.append(info_img) 
© www.soinside.com 2019 - 2024. All rights reserved.