【发布时间】:2021-04-10 02:35:21
【问题描述】:
我对 python 比较陌生,并且遇到了 schedule 的一些问题。我有一个简单的 BeautifulSoup 代码,它可以解析一些来自 usatoday 的新闻标题。
class Command(BaseCommand):
def handle(self, *args, **options):
html = urlopen('')
soup = BeautifulSoup(html, 'html.parser')
site_json=json.loads(soup.text)
for i in range(len(site_json)):
title = site_json[i]['title']
try:
Job.objects.create(
title=title,)
print('%s added' % (title,))
except Exception as e: print(e)
# print('%s already exists' % (title,))
self.stdout.write( 'job complete' )
我的代码运行良好,但我尝试添加计划以每 5 秒运行一次。 (它只是测试)
import time
import schedule
from os import system
def sch():
class Command(BaseCommand):
def handle(self, *args, **options):
html = urlopen('')
soup = BeautifulSoup(html, 'html.parser')
site_json=json.loads(soup.text)
for i in range(len(site_json)):
title = site_json[i]['title']
try:
Job.objects.create(
title=title,)
print('%s added' % (title,))
except Exception as e: print(e)
# print('%s already exists' % (title,))
self.stdout.write( 'job complete' )
schedule.every(5).seconds.do(sch)
while True:
schedule.run_pending()
time.sleep(1)
为了执行 py,什么都没有发生,只是在 shell 处闪烁。我没有任何输出\错误日志。那是因为我不知道该怎么做。我该如何解决这个问题?
【问题讨论】:
-
有必要使用
Command类吗?他们的方式你尝试使用时间表是正确的。也许尝试改用 crontab?
标签: python python-3.x function html-parsing