Search code examples
pythonweb-scrapingredditpraw

İmage scraping from subreddit with python


I'm trying to make a tool that will take photos from any subreddit with python and save them in a specific folder.I can do this, but when I want to use it, I will have to make changes by opening the codes. How can I do this by getting input from the terminal? Like here,

python main.py -s <subreddit> -d <directory> -u <url> -c <category> -l <limit>

Solution

  • Accept arguments in your function:

    def scraper(sub, directory, url, category, limit):
        #your code
    

    So everything after the running of the script will be in those arguments:

    python3 testing.py subreddit directory url category limit
    

    If you don't know how many inputs you are expecting use **args or **kwargs:

    def scraper(**args)
    

    You can read more about args and kwargs here

    EDIT: You can use sys.argv[1] to get certain arguments, make sure to import sys:

    subreddit = sys.argv[1]
    

    If I typed "python3 script.py banana" and printed the variable "subreddit", the output of the code above would be "banana"