0

I am using praw to extract data room reddit i want to get the submission title id and the comments however the for loop that gets the comments for each submission makes it only print one submission and the comments for that submission however it should be 10 posts.


subred = reddit.subreddit("apexlegends")

hot_apex = subred.top(limit=10)

items = hot_apex

first = next(items)
print('first item:', first)

comment = reddit.submission(id=items)

print (type(comment)



for item in items:

    print ('NEW POST--',item.title,'post id --', item) 

    i = str(item)

    sub_id = reddit.submission(id=i)

    for comment in sub_id.comments: 

        print (comment.body)
Andrew Ryan
  • 1,489
  • 3
  • 15
  • 21

1 Answers1

0

The reason why the for loop isn't running correctly is that you are trying to access the elements before using them in the for loop.

You should remove

items = hot_apex

first = next(items)
print('first item:', first)

comment = reddit.submission(id=items)

print (type(comment)

to make your code

subred = reddit.subreddit("apexlegends")
hot_apex = subred.top(limit=10)

for item in hot_apex:
    print ('NEW POST--',item.title,'post id --', item) 
    sub_id = reddit.submission(id=item)

    for comment in sub_id.comments: 
        print (comment.body)

This is because the next() operator is like traversal down a singly linked list not being able to index anything in the array, which you could traverse with a while loop by continuing to do next() inside that while loop. But using the for loop you have constructed this would be the proper way to access the elements.

The reason you aren't getting more comments is that you are only getting the top-level comments and are not getting their children. You should look at this to get the other comments for that post.

Get all comments from a specific reddit thread in python

Andrew Ryan
  • 1,489
  • 3
  • 15
  • 21