Search code examples
pythonredditpraw

Getting child-comments of a comment on Reddit with Praw in Python


I'm using praw to scrape information from a reddit thread. I can use r.get_submission(thread).comments to give me all the comments in a thread, but now I want to iterate through all of those comments and get the child comments.

Here's what I have:

r = praw.Reddit(user_agent="archiver v 1.0")
thread = "https://www.reddit.com/r/AskReddit/comments/4h4o7s/what_do_you_regret_doing_at_university/"
r.login(settings['username'], settings['password'], disable_warning=True)
submission = r.get_submission(thread)

for comment in submission.comments:
    #this works, prints out the comments text
    print(comment.body)

    #now i want to get the child comments that are replied to this comment
    commentSubmission = r.get_submission(comment.permalink)
    #ideally comments[0] should show me first reply, comments[1] the second. etc
    print(commentSubmission.comments[1])

This throws IndexError: list index out of range. I'm using the method of trying to get the comment as a submission because it's similiar to a solution I saw here when I was researching https://www.reddit.com/r/redditdev/comments/1kxd1n/how_can_i_get_the_replies_to_a_comment_with_praw/

My question is: Given a praw comment object, how can I loop through all the child comments that are replies? I want to get all the comments that are direct replies to another comment object.

For example, in the example thread in my program, the first comment is Not going out freshman yearI want to get the response comments like Meh, I never went out at all in college. and Your story sounds identical to mine


Solution

  • It is a simple as comment.replies, it returns the same kind of iterable as submission.comments with Comment and MoreComments Objects, the latter for more comments at the same level.

    Some example code:

    submission = r.get_submission(thread)
    process_comments(submission.comments)
    
    def process_comments(objects):
        for object in objects:
            if type(object).__name__ == "Comment":
                process_comments(object.replies) # Get replies of comment
    
                # Do stuff with comment (object)
    
            elif type(object).__name__ == "MoreComments":
                process_comments(object.comments()) # Get more comments at same level