[英]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. 我有以下代码,应该从reddit.com/r/showerthoughts中随机发一个顶级帖子,并打印该帖子的标题和作者。
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")
You cannot load json directly from a url, for that you need to use requests
module. 您不能直接从URL加载json,因为您需要使用requests
模块。
Using json module 使用json模块
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 不使用json模块
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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.