Search code examples
pythonpraw

AttributeError: 'Submission' object has no attribute 'poll_data' in PRAW


I am trying to access the titles and polls of Reddit posts from the subreddit r/WouldYouRather for a game that I am working on. In the code below, I have attempted to access 10 such posts, obtaining the titles of the submissions, as well as the options of the polls that users have put up. However, when I run the code, I am given an error that says that the poll_data attribute doesn't exist for the Submissions object, which, as far as I can tell, isn't true.

Forgive me for my arbitrary variable names, but here is what I have.

import os
import praw

reddit = praw.Reddit(client_id = 'H'],
                    client_secret = 'H'], 
                    username = 'H'], 
                    password = 'H'], 
                    user_agent = 'H')

lmao = []
lmaolmao = []

sub = reddit.subreddit("wouldyourather")

hotstuff = sub.hot(limit = 10)


for submission in hotstuff:
  lmao.append(submission.title)
  lmaolmao.append(submission.poll_data.options)

print(lmao)
print(lmaolmao)

When I take out any code regarding poll_data, the list of post titles print just fine, so I'm not sure why this code is erroring. Why is this happening?

Edit:

I simplified the code as much as possible, but still got the same error message:

import os
import praw

reddit = praw.Reddit(client_id = os.environ['client_id'],
                    client_secret = os.environ['client_secret'], 
                    username = os.environ['username'], 
                    password = os.environ['password'], 
                    user_agent = os.environ['user_agent'])

sub = reddit.subreddit("wouldyourather").hot(limit = 1)

for submission in sub:
  print(submission.poll_data.options)

Solution

  • Simple answer: The hottest post is not a poll and therefore it does not have the poll_data attribute. I think the hottest post is just the introduction for the subreddit.

    I updated your code to check if the post has the attribute poll_data, which inserts all posts with the poll data to your list:

    lmao = []
    lmaolmao = []
    
    sub = reddit.subreddit("wouldyourather")
    
    hotstuff = sub.hot(limit = 10)
    
    for submission in hotstuff:
      lmao.append(submission.title)
    
      if hasattr(submission, 'poll_data'):
        lmaolmao.append(submission.poll_data.options)
    
    print(lmao)
    print(lmaolmao)
    
    

    The if checks with hasattr() if the submission has poll data otherwise it will be ignored.