Skip to content

Instantly share code, notes, and snippets.

@hanleybrand
Created December 6, 2012 03:56
Show Gist options
  • Save hanleybrand/4221658 to your computer and use it in GitHub Desktop.
Save hanleybrand/4221658 to your computer and use it in GitHub Desktop.
Download images with Requests: HTTP for Humans
import requests
from io import open as iopen
from urlparse import urlsplit
def requests_image(file_url):
suffix_list = ['jpg', 'gif', 'png', 'tif', 'svg',]
file_name = urlsplit(file_url)[2].split('/')[-1]
file_suffix = file_name.split('.')[1]
i = requests.get(file_url)
if file_suffix in suffix_list and i.status_code == requests.codes.ok:
with iopen(file_name, 'wb') as file:
file.write(i.content)
else:
return False
@firstworldproblems
Copy link

the url can be unreliable when it comes to determining file extension. using the header may be better:

if i.headers['Content-Type'].split('/')[1] in suffix_list ...

@revsuine
Copy link

Hey, would you mind if I used this in a small personal program? Obviously no money made etc etc. I only ask since no license is specified.

@yaron148
Copy link

Hey hanleybrand, when i run it for url
https://www.nytimes.com/section/todayspaper

no error occur- but where the images downloaded?

@numberisnan
Copy link

numberisnan commented Jan 31, 2019

Hey hanleybrand, when i run it for url
https://www.nytimes.com/section/todayspaper

no error occur- but where the images downloaded?

You are not directly asking for an image file. This will work for something like https:///.[image file extension]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment