安装schedule库
首先,确保你已经安装了schedule库。如果没有安装,可以使用以下命令进行安装:
pip install schedule
python每日定期分享诗歌
import json
import requests
import schedule
import time
def get_poem():
# 这里使用一个公开的诗歌API,你可以替换为你喜欢的诗歌API或数据库
url = "https://v1.jinrishici.com/shuqing"
response = requests.get(url)
if response.status_code == 200:
# 解析JSON数据
data = response.json()
# 输出json数据
# print(json.dumps(data, ensure_ascii=False, indent=4))
content = data["content"]
author = data["author"]
poem = content + "作者:" + author
return poem
else:
print(f"请求失败,状态码:{response.status_code}")
def share_poem():
poem = get_poem()
print("今日诗歌分享:\n", poem)
# 每天早上9:30点分享一首诗歌
schedule.every().day.at("9:30").do(share_poem)
# share_poem()
while True:
schedule.run_pending()
time.sleep(60)
直接输出
import json
import requests
import schedule
import time
def get_poem():
# 这里使用一个公开的诗歌API,你可以替换为你喜欢的诗歌API或数据库
url = "https://v1.jinrishici.com/shuqing"
response = requests.get(url)
if response.status_code == 200:
# 解析JSON数据
data = response.json()
content = data["content"]
author = data["author"]
poem = content + "作者:" + author
return poem
else:
print(f"请求失败,状态码:{response.status_code}")
def share_poem():
poem = get_poem()
print("今日诗歌分享:\n", poem)
share_poem()
今日诗歌分享:
卧龙跃马终黄土,人事音书漫寂寥。作者:杜甫