【问题标题】:Periodically running a function in python在python中定期运行一个函数
【发布时间】:2017-11-20 14:13:21
【问题描述】:

我有以下函数,它从网页获取一些数据并存储在字典中。时间戳作为键,数据(列表)作为值。

def getData(d):

    page = requests.get('http://www.transportburgas.bg/bg/%D0%B5%D0%BB%D0%B5%D0%BA%D1%82%D1%80%D0%BE%D0%BD%D0%BD%D0%BE-%D1%82%D0%B0%D0%B1%D0%BB%D0%BE')
    soup = BeautifulSoup(page.content, 'html.parser')

    table = soup.find_all("table", class_="table table-striped table-hover")
    rows = table[0].find_all('tr')

    table_head = table[0].find_all('th')
    header = []
    tr_l = []

    rows = []
    for tr in table[0].find_all('tr'):
        value = tr.get_text()
        rows.append(value)

    time_stamp = rows[1].split("\n")[1]
    data = []
    for i in rows[1:]:
        a = i.split("\n")
        if time.strptime(a[1], '%d/%m/%Y %H:%M:%S')[:4] == time.localtime()[:4]:
            data.append(int(a[3]))
        else:
            data.append(np.nan)

    d[time_stamp] = data

网页上的数据每 5 分钟更新一次。我想让该功能每 5 分钟自动运行一次。我正在尝试使用 time.sleep 和此功能:

def period_fun(it):
    iterations = it 
    while iterations != 0:
        getData(dic)
        time.sleep(300)
        iterations = iterations -1

但是,这个函数只运行一次,我最终在字典中只有一个项目。我已经尝试使用简单的 print (1) 而不是函数并且它可以工作(1 被打印多次),但是当我用函数实现它时它不起作用。

非常感谢有关功能或如何实现目标的任何建议!

最好的问候, 姆拉登

【问题讨论】:

  • 你试过使用 cron 吗?
  • 您可以使用threading.Timer 对象定期调用函数。

标签: python-3.x function web-scraping


【解决方案1】:

使用一些使用 cron 作业的库怎么样?

Schedule 看起来不错,虽然它没有使用类似 cron 的语法:https://github.com/dbader/schedule

【讨论】:

    猜你喜欢
    • 2017-03-14
    • 1970-01-01
    • 2019-05-18
    • 2016-11-27
    • 1970-01-01
    • 2016-10-27
    • 1970-01-01
    • 2012-06-04
    • 2021-12-16
    相关资源
    最近更新 更多