在Python中,定时启动爬虫任务可以通过以下几种方法实现:
方法一:使用 `crontab`
2. 打开终端,输入 `crontab -e` 编辑crontab文件。
3. 在文件末尾添加一行,格式为 `* * * * * /path/to/script.py`,其中 `*` 表示每个小时、分钟和秒都运行一次。
4. 保存并退出crontab,按 `Y` 确认保存。
方法二:使用 `schedule` 库
1. 安装 `schedule` 库,使用 `pip install schedule`。
2. 编写Python脚本,导入 `schedule` 和 `time` 模块。
3. 使用 `schedule.every().day.at("HH:MM").do(job)` 定义任务,其中 `HH:MM` 是任务执行的具体时间。
4. 在 `while True` 循环中调用 `schedule.run_pending()` 来运行挂起的任务。
方法三:使用 `time` 模块
1. 编写Python脚本,使用 `time.sleep` 函数来等待特定时间。
2. 在 `while True` 循环中,使用 `time.strftime` 检查当前时间是否等于设定的时间,如果是则执行任务。
方法四:使用 `datetime` 模块
1. 编写Python脚本,使用 `datetime` 模块检查当前日期是否为每天。
2. 如果是每天,则执行爬虫任务。
示例代码(使用 `crontab`)
```
每天凌晨3点执行爬虫任务
0 3 * * * /path/to/script.py
示例代码(使用 `schedule` 库)
```python
import schedule
import time
def job():
这里编写爬虫代码
print('爬虫任务执行中...')
每隔5分钟执行一次
schedule.every(5).minutes.do(job)
while True:
schedule.run_pending()
time.sleep(1)
选择适合您需求的方法进行定时任务的设置。