2

I have been reading through alot of documentation around Praw, bs4 and I've had a look at other peoples examples of how to do this but I just can't get anything working the way I would like. I thought it would be a pretty simple script but every example I find is either written in python2 or just doesn't work at all.

I would like a script to download the top 10 images from a given Subreddit and save them to a folder.

If anyone could point me in the write direction that would be great. Cheers

Oli Shingfield
  • 109
  • 1
  • 9

1 Answers1

4

The high level flow will look something like this -

  1. Iterate through the top posts of your subreddit.
  2. Extract the url of the submission.
  3. Check if the url is an image.
  4. Save the image to your desired folder.
  5. Stop once you have 10 images.

Here's an example of how this could be implemented-

import urllib.request

subreddit = reddit.subreddit("aww")
count = 0

# Iterate through top submissions
for submission in subreddit.top(limit=None):

    # Get the link of the submission
    url = str(submission.url)

    # Check if the link is an image
    if url.endswith("jpg") or url.endswith("jpeg") or url.endswith("png"):

        # Retrieve the image and save it in current folder
        urllib.request.urlretrieve(url, f"image{count}")
        count += 1

        # Stop once you have 10 images
        if count == 10:
            break
Harshith Bolar
  • 728
  • 1
  • 10
  • 29
  • Hi thanks for the reply, I've tried your code but its giving me the error: Traceback (most recent call last): File "E:/Users/Oli Shingfield/Documents/Projects//test4.py", line 7, in for submission in subreddit.top(limit=None): AttributeError: 'str' object has no attribute 'top' -------------- Any ideas? – Oli Shingfield Apr 17 '19 at 21:51