You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python3中每2小时执行命令行或单元格?(含Selenium脚本场景)

实现每2小时重复执行Selenium脚本的方案

一、Jupyter Notebook 中重复执行最后一个单元格

直接在目标单元格中加入循环+延时逻辑,同时注意释放Selenium资源避免内存泄漏:

import time
from selenium import webdriver

def run_selenium_task():
    # 替换为你的Selenium业务代码
    driver = webdriver.Chrome()
    try:
        driver.get("https://example.com")
        # 此处编写你的具体操作逻辑
    finally:
        # 无论执行结果如何,确保关闭浏览器
        driver.quit()

# 无限循环,每2小时执行一次任务
while True:
    run_selenium_task()
    # 2小时换算为秒:2*60*60
    time.sleep(2 * 60 * 60)

如果不想阻塞Notebook的其他操作,可以用后台线程执行:

import time
import threading
from selenium import webdriver

def run_selenium_task():
    driver = webdriver.Chrome()
    try:
        driver.get("https://example.com")
        # 你的业务代码
    finally:
        driver.quit()

def repeat_task():
    while True:
        run_selenium_task()
        time.sleep(2 * 60 * 60)

# 启动后台守护线程,关闭Notebook时自动终止
threading.Thread(target=repeat_task, daemon=True).start()

二、命令行环境下重复执行

1. 脚本内部实现循环

编写包含循环逻辑的Python脚本(例如命名为selenium_task.py),直接在命令行运行:

# selenium_task.py
import time
from selenium import webdriver

def run_task():
    driver = webdriver.Chrome()
    try:
        driver.get("https://example.com")
        # 你的业务代码
    finally:
        driver.quit()

if __name__ == "__main__":
    while True:
        run_task()
        time.sleep(2 * 60 * 60)

运行命令:

python3 selenium_task.py

2. 系统定时任务(更稳定推荐)

如果不想让脚本持续占用终端,可借助系统定时工具:

  • Linux/macOS:使用cron
    1. 打开crontab编辑界面:
      crontab -e
      
    2. 添加定时规则(每2小时执行一次):
      0 */2 * * * /usr/bin/python3 /绝对路径/selenium_task.py
      
      注意替换为你的Python实际路径和脚本绝对路径。
  • Windows:使用「任务计划程序」
    1. 创建基本任务,设置触发器为「每2小时执行一次」
    2. 操作选择「启动程序」,程序路径选Python.exe,参数填脚本的绝对路径。

内容的提问来源于stack exchange,提问作者Herobe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 02:35:17