Python请求在下载图像时显示400错误请求

时间:2019-05-29 09:32:55

标签: python python-3.x python-requests

我有为各种图像给出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,它返回400个错误代码。

0 个答案:

没有答案