forked from ohhdemgirls/RedditImageGrab
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreddit.py
executable file
·43 lines (35 loc) · 1.38 KB
/
reddit.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
#!/usr/bin/env python
"""Return list of items from a sub-reddit of reddit.com."""
import sys
from urllib2 import urlopen, Request, HTTPError
from json import JSONDecoder
def getitems(subreddit, previd=''):
"""Return list of items from a subreddit."""
url = 'http://www.reddit.com/r/%s.json' % subreddit
# Get items after item with 'id' of previd.
hdr = { 'User-Agent' : 'RedditImageGrab script.' }
if previd:
url = '%s?after=t3_%s' % (url, previd)
try:
req = Request(url, headers=hdr)
json = urlopen(req).read()
data = JSONDecoder().decode(json)
items = [x['data'] for x in data['data']['children']]
except HTTPError as ERROR:
error_message = '\tHTTP ERROR: Code %s for %s.' % (ERROR.code, url)
sys.exit(error_message)
except ValueError as ERROR:
if ERROR.args[0] == 'No JSON object could be decoded':
error_message = 'ERROR: subreddit "%s" does not exist' % (subreddit)
sys.exit(error_message)
raise ERROR
return items
if __name__ == "__main__":
print 'Recent items for Python.'
ITEMS = getitems('python')
for ITEM in ITEMS:
print '\t%s - %s' % (ITEM['title'], ITEM['url'])
print 'Previous items for Python.'
OLDITEMS = getitems('python', ITEMS[-1]['id'])
for ITEM in OLDITEMS:
print '\t%s - %s' % (ITEM['title'], ITEM['url'])