如何在Python脚本中重新加载URL数据或每小时重新运行脚本?

0 投票
2 回答
52 浏览
提问于 2025-04-14 16:27

我正在从一个网址抓取数据,这个网址的内容经常会变化,然后用Flask来展示这个页面。现在我想知道,怎样才能每小时重新抓取一次数据,并把它发送到Flask?

  • 我应该使用APSchedule吗?
  • 还是用Windows的任务调度器?(如果用的话,怎么结束当前正在运行的脚本呢?)
  • 或者有没有办法在脚本里定期重新加载和更新数据?(如果有的话,能不能给我一个具体的实现示例?我在学习Python时遇到了一些困难。)

我试过一些APSchedule的例子,但没有成功。下面是我的代码:

#News feed test for Xibo Signage
from flask import Flask, render_template
from markupsafe import Markup
app=Flask(__name__) 
from urllib.request import Request, urlopen
from bs4 import BeautifulSoup
import requests
from datetime import datetime

# datetime object containing current date and time
# dd/mm/YY H:M:S
now = datetime.now()
current_time = now.strftime("%d/%m/%Y %H:%M:%S")

url = "https://news.clemson.edu/tag/extension/"
soup = BeautifulSoup(requests.get(url, headers={'user-agent':'Mozilla/5.0'}).text)
picture=[]
for e in soup.select('article img.lazyload'):
    sorce = (e.get('data-src'))
    picture.append(sorce)


title=[]
for e in soup.select('article header'): 
    etitle =  (e.find("h3", class_="entry-title bold").text)
    title.append(etitle)
    #    print(e.find("h3", class_="entry-title bold"))
pictures = picture
titles = title

@app.route('/') 
def home():
    return render_template('home.html',pictures=pictures, titles=titles, current_time=current_time)

if __name__ == '__main__':

    app.run(host='0.0.0.0')
    app.run(debug=True)

我搞不清楚怎么把函数正确地放到调度任务里。我让脚本运行得不错,但Flask页面上的时间/日期没有更新。

from apscheduler.schedulers.background import BackgroundScheduler

now = datetime.now()
current_time = now.strftime("%d/%m/%Y %H:%M:%S")

def sensor():
    """ Function for test purposes. """
    now = datetime.now()
    current_time = now.strftime("%d/%m/%Y %H:%M:%S")
    print("Scheduler is alive!")

sched = BackgroundScheduler(daemon=True)
sched.add_job(sensor,'interval',minutes=5)
sched.start()

它只在我第一次运行脚本时设置了一次时间日期。

2 个回答

0

试试 nssm.exe,它可以把你的应用程序变成一个服务,这样它就能在Windows启动时自动运行,并且在后台工作。

我通常用 choco 来安装 nssm.exe:

choco install nssm

然后重启你的命令行窗口,输入:

nssm install flask

这时会弹出一个简单的图形界面。只需要把你的Python程序以命令行的形式设置进去就可以了。

0

通常,我会把这个任务当作一个一次性的脚本来运行,可以用Windows的任务计划程序、cron(在Linux上用的定时任务工具)或者GitHub的自动化功能,然后把数据写入一个文件。接着,我会让Flask应用读取这个文件,并在有人请求时提供数据。

但是,如果你想让这个任务在Flask应用内部运行,并且可以选择不把数据保存到文件里,你可以使用Flask-APScheduler来安排这个任务,方法如下:

# python 3.10.12
from datetime import datetime
from flask import Flask # 3.0.2
from flask_apscheduler import APScheduler # 1.13.1


class Config:
    SCHEDULER_API_ENABLED = True


class Time:
    now = datetime.now()


app = Flask(__name__)
app.config.from_object(Config())
scheduler = APScheduler()
scheduler.init_app(app)
scheduler.start()


@scheduler.task("interval", id="sensor", seconds=5)
def sensor():
    Time.now = datetime.now()
    print("job ran:", Time.now)


@app.get("/")
def index():
    return {"last_job_time": Time.now.strftime("%d/%m/%Y %H:%M:%S")}


if __name__ == "__main__":
    app.run()

启动服务器后的示例输出:

$ curl localhost:5000
{"last_job_time":"13/03/2024 12:10:11"}
$ curl localhost:5000
{"last_job_time":"13/03/2024 12:10:11"}
$ curl localhost:5000
{"last_job_time":"13/03/2024 12:10:16"}
$ curl localhost:5000
{"last_job_time":"13/03/2024 12:10:16"}

撰写回答