manga-dlp/mangadexdlp/downloader.py

35 lines
884 B
Python
Raw Normal View History

2021-12-19 17:20:34 +01:00
import shutil
import requests
from time import sleep
from pathlib import Path
2021-12-20 15:33:04 +01:00
def download_chapter(image_urls, chapter_path, md_wait=0.5, md_verbose=False):
2021-12-19 17:20:34 +01:00
# download images
2021-12-19 19:44:19 +01:00
img_num = 1
2021-12-19 17:20:34 +01:00
for img in image_urls:
# set image path
2021-12-19 19:44:19 +01:00
image_path = Path(f'{chapter_path}/{img_num:03d}')
2021-12-19 17:20:34 +01:00
try:
2021-12-19 19:44:19 +01:00
#print('Try getting ' + img)
2021-12-19 17:20:34 +01:00
req = requests.get(img, stream = True)
except:
2021-12-20 14:29:40 +01:00
print(f'Request for image {img} failed, retrying')
2021-12-20 15:33:04 +01:00
sleep(md_wait)
2021-12-19 17:20:34 +01:00
req = requests.get(img, stream = True)
if req.status_code == 200:
req.raw.decode_content = True
with image_path.open('wb') as file:
shutil.copyfileobj(req.raw, file)
# verbose logging
2021-12-20 15:33:04 +01:00
if md_verbose:
print(f' Downloaded image {img_num}')
2021-12-19 17:20:34 +01:00
img_num += 1
2021-12-19 19:44:19 +01:00
sleep(0.5)
2021-12-19 17:20:34 +01:00
else:
print('Image {img} could not be downloaded. Exiting')
2021-12-19 17:20:34 +01:00
exit(1)