Search code examples
pythonpython-2.7praw

How do I use PRAW and python to retrieve reddit post data from a certain user?


Python version : 2.7

I am trying to retrieve posts from a Reddit user and store them in python into a variable. Below is an example of what I am trying to accomplish. It should get ALL posts from the user. Please note that most of the below code, attributes and commands are by no means correct ; just there to illustrate my intentions.

...

r = praw.Reddit(user_agent=user_agent)
uname : "/u/test"
count = r.get_total_amount_of_post(username=uname)
durl = "https://www.reddit.com/user/Sariel007"
m_data = [" "] * count 

from a in range (0,count)
 m_data[a] = " ".join(r.next(r.get_content(url=durl)))

...

I have tried the get_content and get_submission classes but nothing that seems remotely close. Lets say the users first post was titled "hello" and its data was "123456789 97635". The next post was "good day" and its data was "abc abc abc". When the code completes, m_data should show :

['123456789 97635','abc abc abc']

Solution

  • The way to accomplish something like this is to read the docs, and make small, simple changes while running your code. https://praw.readthedocs.org/

    Trying to write the whole thing at once just isn't possible. You need to start by running a program that can import praw, then one that can create a praw object, then one that can get a user, and so on. Here's a few more tips:

    1. Print everything.
    2. Try printing variable.__dict__ on a variable if you don't know what can be done with it.
    3. Start small, and when you have a problem post mostly-working code to Stack Overflow.

    This code will do what you're trying to do, print all the selftest of the submitted links for a user:

    from pprint import pprint
    import praw
    
    r = praw.Reddit(user_agent='praw_overflow')
    user = r.get_redditor('Sariel007')
    submissions = user.get_submitted()
    
    self_texts = []
    for link in submissions:
        self_texts.append(link.selftext)
    
    print self_texts
    

    The user Sariel007 doesn't have any recent self-posts, so it just prints empty strings right now, but I tried it on another user and it worked.