Jack
Jack

Reputation: 45

How to get random top posts from reddit.com/r/showerthoughts

I have the following code that is supposed to take a random top post from reddit.com/r/showerthoughts and print the title and author of the post.

import  random, json
randnum = random.randint(0,99)
response = json.load('https://www.reddit.com/r/showerthoughts/top.json?sort=top&t=week&limit=100')["data"]["children"][randnum]["data"]
print("\n\"" + response["title"] + "\"")
print("    -" + response["author"] + "\n")

I get the following error:

Traceback (most recent call last):
  File "C:/Users/jacks/.PyCharmCE2019.1/config/scratches/scratch_4.py", line 4, in <module>
    response = json.load('https://www.reddit.com/r/showerthoughts/top.json?sort=top&t=week&limit=100')["data"]["children"][randnum]["data"]
  File "C:\Users\jacks\AppData\Local\Programs\Python\Python37\lib\json\__init__.py", line 293, in load
    return loads(fp.read(),
AttributeError: 'str' object has no attribute 'read'

Am I on the right track here?

UPDATE: Got it to work with this code:

import  random, requests
randnum = random.randint(0,99)
response = requests.get('https://www.reddit.com/r/showerthoughts/top.json?sort=top&t=week&limit=100', headers = {'User-Agent': 'showerbot'})
result = response.json()
result1 = result["data"]["children"][randnum]["data"]
print("\n\"" + result1["title"] + "\"")
print("    -" + result1["author"] + "\n")

Upvotes: 0

Views: 214

Answers (1)

CodeIt
CodeIt

Reputation: 3618

You cannot load json directly from a url, for that you need to use requests module.

Using json module

import  random, json, requests
randnum = random.randint(0,99)

response = requests.get('https://www.reddit.com/r/showerthoughts/top.json?sort=top&t=week&limit=100')

response = json.loads(response.text)
response = response["data"]["children"][randnum]["data"]

print("\n\"" + response["title"] + "\"")
print("    -" + response["author"] + "\n")

Without using json module

import  random,  requests
randnum = random.randint(0,99)

response = requests.get('https://www.reddit.com/r/showerthoughts/top.json?sort=top&t=week&limit=100')

response = response.json()
response = response["data"]["children"][randnum]["data"]

print("\n\"" + response["title"] + "\"")
print("    -" + response["author"] + "\n")

Upvotes: 1

Related Questions