Python请求在下载图像时说有400个错误请求

2024-03-29 15:58:01 发布

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

我有代码,这是给400个不同的图像坏请求。下面是代码

def gen_random_text():
    return uuid.uuid4().hex


def dl_img(image_url):
    file_name = ''
    extension = 'jpg'
    print('Downloading Image..' + image_url)
    choices = [3, 6, 9, 1, 2]
    sleep(1)

    if '.png' in image_url:
        extension = 'png'

    try:
        headers = {
            'user-agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36',
            'referer': 'https://google.ca',
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
            'Accept-Encoding': 'gzip, deflate, br',
            'Accept-Language': 'en-US,en;q=0.9,ur;q=0.8',
            'Cache-Control': 'no-cache',
            'Pragma': 'no-cache',
            'Upgrade-Insecure-Requests': '1'
        }
        print('IMAGE URL = '+image_url.strip())
        response = requests.get(image_url, headers=headers, timeout=30,allow_redirects=True)

        print('Status Code = {}'.format(response.status_code))

        if response.status_code == 200:
            file_name = gen_random_text() + '.' + extension
            file_path = LOCAL_PATH + file_name

            with open(file_path, 'wb') as fi:
                fi.write(response.content)

    except Exception as ex:
        print('Exception while downloading')
        print(str(ex))
        exc_type, exc_obj, exc_tb = sys.exc_info()
        fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
        print(exc_type, fname, exc_tb.tb_lineno)
        file_name = None
    finally:
        return file_name

其中一个图像是:

https://i.kinja-img.com/gawker-media/image/upload/s--n3niXKMn--/c_scale,f_auto,fl_progressive,q_80,w_800/ckp2wdnwovpejo0tcgsa.jpg  which returns 400 error code.

Tags: pathtextnameimageurlapplicationresponseextension