-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathredditpics.py
56 lines (45 loc) · 1.6 KB
/
redditpics.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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# this is the one you'll need to "pip install praw"
import praw
# these should be standard
import re
import urllib.request
import os
from pathlib import Path
# account setup
reddit = praw.Reddit(
client_id="client_id_here",
client_secret="client_secret_here",
user_agent="Mozilla",
)
# subreddit parameters
# these give about 150 images when I tried it
whichSubreddit = 'ImaginaryLandscapes'
articleCount = 1000
minScore = 300
# whichSubreddit = 'mostbeautiful'
# articleCount = 1000
# minScore = 100
# whichSubreddit = 'earthporn'
# articleCount = 1000
# minScore = 200
subreddit = reddit.subreddit(whichSubreddit)
# make the corresponding subdirectory
if not os.path.exists(whichSubreddit):
os.makedirs(whichSubreddit)
# loop through the hot submissions
for submission in subreddit.hot(limit=articleCount):
sub_id = submission.id # Output: the submission's ID
# check for image and score
if('preview' in vars(submission) and submission.score > minScore):
url = vars(submission)['preview']['images'][0]['source']['url']
# I've only seen .jpg files, but just to make sure
baseUrl = url.split('?')[0]
suffix = Path(baseUrl).suffix
# munge title into filename
localFileName = "_".join( submission.title.split() )
localFileName = re.sub(r'\W+', '', localFileName.title()) + suffix
print(localFileName)
localFilePath = whichSubreddit + '/' + localFileName
# download and store if we don't have it already
if(not os.path.isfile(localFilePath)):
urllib.request.urlretrieve(url, localFilePath)