-
Notifications
You must be signed in to change notification settings - Fork 0
/
reddit_scraper.py
281 lines (227 loc) · 9.06 KB
/
reddit_scraper.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
import praw
import prawcore
import requests
import os
from RedDownloader import RedDownloader
from data.config_cred import *
# REDDIT SCRAPER by dsplayerX
def initReddit():
global reddit
if os.path.exists(os.getcwd() + "/data/creds.txt"):
creds = decodeCreds()
userID = creds[0]
userSecret = creds[1]
else:
print("> Credits token not found! Enter your details below to create one.")
userID = input("Enter your Client ID: ")
userSecret = input("Enter your Client Secret: ")
encodeCreds(userID, userSecret)
print("> Credentials saved!")
reddit = praw.Reddit(
client_id=userID,
client_secret=userSecret,
user_agent="reddit-scraper",
username="",
password="",
)
def scrapePosts(sub_name, sub_sort, scrape_limit):
subreddit = reddit.subreddit(sub_name)
postCount = 0
if os.path.exists(os.getcwd() + "/savedscrapes"):
pass
else:
os.mkdir(os.getcwd() + "/savedscrapes")
print(f" > Scraping {scrape_limit} posts from r/{sub_name}...")
try:
with open("savedscrapes/" + sub_name + "-" + str(sub_sort) + "-" + str(scrape_limit) + ".txt", "a", encoding="utf-8") as file:
for submission in getSortedSubreddit(subreddit, sub_sort)(limit = scrape_limit):
postCount += 1
permaURL = "https://www.reddit.com/"+submission.permalink
print("\n > " + str(postCount) + ". " + submission.title)
print(" - " + permaURL)
# print(submission.url)
file.write("\n\n" + str(postCount) + ". " + submission.title)
file.write(" - " + permaURL)
file.close()
print(f"\n > Found {postCount} post(s).")
except (prawcore.exceptions.NotFound, prawcore.exceptions.Redirect):
print(">> ERROR: Invalid Subreddit!")
except (praw.exceptions.PRAWException, prawcore.exceptions.PrawcoreException) as e:
print(">> ERROR: Reddit API Error - " + e)
userSave = input("\nSave scraped posts? (y/n) : ")
if userSave.lower() == "y" or userSave.lower() == "yes":
print(" > Saved data to a text file successfully!")
else:
if os.path.exists(os.getcwd() + "/savedscrapes/" + sub_name + "-" + str(sub_sort) + "-" + str(scrape_limit) + ".txt"):
os.remove(os.getcwd() + "/savedscrapes/" + sub_name + "-" + str(sub_sort) + "-" + str(scrape_limit) + ".txt")
else:
pass
print(" > Removed saved cache...")
def scrapeImages(sub_name, sub_sort, scrape_limit):
if os.path.exists(os.getcwd() + "/images"):
pass
else:
os.mkdir(os.getcwd() + "/images")
subreddit = reddit.subreddit(sub_name)
imageCount = 0
galleryCount = 0
print(f" > Scraping {scrape_limit} posts from r/{sub_name} for images...")
try:
for submission in getSortedSubreddit(subreddit, sub_sort)(limit = scrape_limit):
subURL = submission.url
if "i.redd.it" in subURL.lower():
if "jpg" in subURL.lower() or "jpeg" in subURL.lower():
image = requests.get(subURL)
with open("images/" + sub_name + "-" + submission.id + ".jpg", "wb") as file:
file.write(image.content)
file.close()
imageCount += 1
elif "png" in subURL.lower():
image = requests.get(subURL)
with open("images/" + sub_name + "-" + submission.id + ".png", "wb") as file:
file.write(image.content)
file.close()
imageCount += 1
elif "gif" in subURL.lower():
image = requests.get(subURL)
with open("images/" + sub_name + "-" + submission.id + ".gif", "wb") as file:
file.write(image.content)
file.close()
imageCount += 1
elif "www.reddit.com/gallery" in subURL.lower():
print()
RedDownloader.Download(url = subURL , output=sub_name + "-" + submission.id , destination="images/")
galleryCount += 1
except (prawcore.exceptions.NotFound, prawcore.exceptions.Redirect):
print(">> ERROR: Invalid Subreddit!")
except (praw.exceptions.PRAWException, prawcore.exceptions.PrawcoreException) as e:
print(">> ERROR: Reddit API Error - " + e)
except:
pass
print(f"\n > Found {imageCount} image(s).")
if imageCount > 0:
print(f" > Saved {imageCount} image(s).")
if galleryCount > 0:
print(f"\n > Found {galleryCount} gallery(s).")
def scrapeVideos(sub_name, sub_sort, scrape_limit, quality):
if os.path.exists(os.getcwd() + "/videos"):
pass
else:
os.mkdir(os.getcwd() + "/videos")
subreddit = reddit.subreddit(sub_name)
videoCount = 0
print(f" > Scraping {scrape_limit} posts from r/{sub_name} for videos...")
try:
for submission in getSortedSubreddit(subreddit, sub_sort)(limit = scrape_limit):
try:
if "v.redd.it" in submission.url.lower():
permaURL = "https://www.reddit.com/"+submission.permalink
RedDownloader.Download(url = permaURL , output=sub_name + "-" + submission.id , destination="videos/" , quality = quality)
# print(permaURL)
videoCount += 1
except:
print(">> ERROR: Video Downloading Failed!")
except (prawcore.exceptions.NotFound, prawcore.exceptions.Redirect):
print(">> ERROR: Invalid Subreddit!")
except (praw.exceptions.PRAWException, prawcore.exceptions.PrawcoreException) as e:
print(">> ERROR: Reddit API Error - " + e)
print(f" > Found {videoCount} video(s).")
def menuChoice():
print("\n------------------")
print("| Reddit Scraper |")
print("------------------")
print("\nSelect what you want to do.")
print("\n 1. Scrape Post URLs")
print(" 2. Scrape Images")
print(" 3. Scrape Videos")
print("\n q. Quit\n")
userChoices = ["1", "2", "3", "q"]
while True:
try:
userChoice = input("Enter your choice: ")
except:
print("Try again!")
continue
else:
if userChoice.lower() in userChoices:
break
else:
print("> Select number from the given options!")
continue
return userChoice
def printSortMethods():
print("\nSorting Methods for Subreddits")
print(" 1. Hot")
print(" 2. New")
print(" 3. Rising")
print(" 4. Gilded")
print(" 5. Controversial")
print(" 6. Top of all time")
def getSortedSubreddit(subreddit, sort):
sub_sort_dict = {
1 : subreddit.hot,
2 : subreddit.new,
3 : subreddit.rising,
4 : subreddit.gilded,
5 : subreddit.controversial,
6 : subreddit.top
}
return sub_sort_dict[sort]
def getUserInputs():
userSub = input("\nEnter subreddit name: ")
printSortMethods()
while True:
try:
userSort = int(input("Enter sort method: "))
except ValueError:
print("> You have to enter an integer!")
continue
else:
if userSort >= 1 and userSort <=6:
break
else:
print("> Select from the options above!")
continue
while True:
try:
userLimit = int(input("How many posts to scrape: "))
except ValueError:
print("> You have to enter an integer!")
continue
else:
break
return userSub, userSort, userLimit
def main():
initReddit()
isRunning = True
while isRunning:
userChoice = menuChoice()
if userChoice == "1":
scrapePosts(*getUserInputs())
elif userChoice == "2":
scrapeImages(*getUserInputs())
elif userChoice == "3":
userInputs = getUserInputs()
# Getting video quality input from user
videoQualities = [360, 480, 720, 1080]
print("\nSelect Video Quality")
print(" > Avaliable options to choose from are 360, 480, 720, 1080")
print(" > If a video file in specified resolution is not found, will try for a lower resolution")
while True:
try:
userQuality = int(input("Enter video quality: "))
except ValueError:
print("> Enter video quality in integers!")
continue
else:
if userQuality in videoQualities:
break
else:
print("> Enter a video quality from the given options!")
scrapeVideos(*userInputs, userQuality)
elif userChoice.lower() == "q":
isRunning = False
else:
print("Wrong input! Try again!")
if __name__ == "__main__":
main()