-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimage_dl.py
33 lines (31 loc) · 1.09 KB
/
image_dl.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import requests, shutil, os
from pathlib import Path
def save_image(link,folder=''):
# Check if a folder was passed, creates it if not exists
if folder != '':
if not os.path.exists(folder):
os.makedirs(folder)
# Gets the filename
filename = link.split('/')[-1:][0]
filename = folder+filename
try:
# Check if file already exists based on filename
# then download and save image
if not Path(filename).is_file():
try:
r = requests.get(link, stream=True)
if r.status_code == 200:
with open(filename, 'wb') as f:
r.raw.decode_content = True
shutil.copyfileobj(r.raw, f)
print('Saved '+filename)
# This is in case the url can't be resolved
except socket.gaierror:
print('Error downloading '+filename)
pass
else:
print('File already exists')
pass
except OSError as e:
print('Weird filename, skipping')
pass