Files
Gists/pin_fetcher.py/pin_fetcher.py
2023-06-19 09:38:01 -04:00

96 lines
3.3 KiB
Python

#!/usr/bin/env python3
##
# Specially useful to make backups of your Pinterest boards when used together with
# the pins_from_cache.js script.
##
import argparse
import requests
import io
import time
from PIL import Image
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Download photos from a Pinterest URL list")
parser.add_argument('-u', '--urls', help='The URL list txt file')
parser.add_argument('-d', '--delay', type=int, default=1, help='Delay in seconds between downloads.')
args = parser.parse_args()
delay = args.delay
resume = False
target = 0
if resume:
with open("log", "r") as log:
target = int(log.readline())
with open(args.urls, "r") as f:
line = 0
for url in f:
try:
if resume and line < target:
continue
success = False
url = url.strip()
# Request the image
print("Fetching: " + url)
req = requests.get(url)
print(req.status_code)
if req.status_code == 200:
# Save the image to file on success.
img = Image.open(io.BytesIO(req.content)).convert('RGB')
img.save(url.split("/")[-1])
success = True
else:
# Attempt to download the image as a PNG on error
url = url.replace(".jpg", ".png")
print("JPG failed")
print("Fetching: " + url)
req = requests.get(url)
print(req.status_code)
if req.status_code == 200:
# Save the image to file on success.
img = Image.open(io.BytesIO(req.content))
img.save(url.split("/")[-1])
success = True
else:
# Attempt to download the image as a GIF on error
url = url.replace(".png", ".gif")
print("PNG failed")
print("Fetching: " + url)
req = requests.get(url)
print(req.status_code)
if req.status_code == 200:
# Save the image to file on success.
with open(url.split("/")[-1], "wb") as f:
# Workaround for a PIL bug when saving GIF files
for chunk in req.iter_content(chunk_size=128):
f.write(chunk)
success = True
elif req.status_code == 403:
# Log the error if JPG, PNG and GIF failed
print("Failed to download: " + url)
# Log the image if the download was successful
if success:
with open("log", "w") as log:
log.write(str(line))
except Exception as e:
print(e)
line += 1
# Wait
time.sleep(delay)