Guest User

earthporn_downloader.py

a guest
Jul 20th, 2020
170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.82 KB | None | 0 0
  1. # Earthporndownloader.py
  2. # Downloads the top images from reddit.com/r/earthporn and saves them to a wallpapers folder
  3.  
  4. import requests
  5. import json
  6. import sys
  7. import uuid
  8. import re
  9. from PIL import Image
  10. import os.path
  11. import os
  12.  
  13.  
  14. if hasattr(sys, 'real_prefix'):
  15.     print("in venv")
  16.  
  17. WALLPAPER_PATH = os.path.dirname(os.path.realpath(__file__))
  18.  
  19. req = requests.get("https://www.reddit.com/r/earthporn.json",
  20.                     headers = {'User-agent' : 'Your Bot 0.1'})
  21.  
  22. if req.status_code != 200:
  23.     print("Error downloading the earthporn.json. Exiting")
  24.     sys.exit()
  25.  
  26. js = json.loads(req.text)
  27.  
  28. children_array = js['data']['children']
  29.  
  30. downloaded_ids = []
  31.  
  32. # Load downloaded IDs
  33. with open('downloaded_images.txt', 'r') as downloaded_images_file :
  34.     for id in downloaded_images_file:
  35.         # Loads as array, remove line endings to make it cleaner/easier to match
  36.         id = id.replace('\n', '').replace('\r', '')
  37.         downloaded_ids.append(id)
  38.  
  39. # Now open the file to append
  40. downloaded_images_file = open('downloaded_images.txt', 'a')
  41.  
  42. path = os.path.abspath(WALLPAPER_PATH)
  43.  
  44. for post in children_array:
  45.     url = post['data']['url']
  46.  
  47.     id = re.match(r"https?://.*/(.*).jpg", url)
  48.  
  49.     # Check if an http url is found
  50.     if id:
  51.         id = id.group(1)
  52.        
  53.         # IF Image has not been downloaded before, download it now
  54.         # Catches issues where you would download duplicates
  55.  
  56.         if(id not in downloaded_ids):
  57.             downloaded_images_file.write(id + "\n")
  58.             filename = os.path.join(path, str(uuid.uuid4()) + ".jpg")
  59.  
  60.             image_request = requests.get(url)
  61.             with open(filename, 'wb') as file:
  62.                 file.write(image_request.content)
  63.            
  64.             # TODO filter by width/height/some other attribute to pick only the high quality monitors that look good for a background
  65.             im = Image.open(filename)
  66.             width, height = im.size
  67.  
  68. downloaded_images_file.close()
Add Comment
Please, Sign In to add comment