Sem
Sem

Reputation: 21

praw: Get body and title of random post in subreddit

I'm trying to print out the title along with the content (body) of a random post on a given subreddit. I've been looking around all over the internet on how to do this, but I cant seem to figure it out.

I've written something down here that gets the id of a random submission.

import praw

reddit = praw.Reddit(
    client_id = "",
    client_secret = "",
    password = "",
    user_agent = "",
    username = "",
)

random_submission = reddit.subreddit('playboicarti').random()

print(random_submission)

Example output:

v206wo

Here it's getting the id of a random submission from the subreddit called playboicarti.

Does anyone know how I'm supposed to print out the title and the content of that submission using the id?

Upvotes: 2

Views: 709

Answers (1)

will-hedges
will-hedges

Reputation: 1284

You can access both the title attributes and the url attributes, print the title and open the url in a browser perhaps?

import webbrowser 
import praw

reddit = praw.Reddit(
    client_id = "",
    client_secret = "",
    password = "",
    user_agent = "",
    username = "",
)

random_submission = reddit.subreddit('playboicarti').random()
print(random_submission.title)
webbrowser.open(random_submission.url)

The nice thing about the url attribute is that it will follow the link, or open the post in the case of a self/text post.

If you wanted to print the context of a text post OR open a link post, you can access the selftext attribute, or open the link like so:

import webbrowser
import praw

reddit = praw.Reddit(
    client_id = "",
    client_secret = "",
    password = "",
    user_agent = "",
    username = "",
)

random_submission = reddit.subreddit('playboicarti').random()
print(random_submission.title)

if random_submission.selftext:
    print(random_submission.selftext)
else:
    # a link post will return a blank string ('falsy'), so open the link
    webbrowser.open(random_submission.url)

Upvotes: 2

Related Questions