在Python中设置定时爬虫,您可以使用`sched`模块或`schedule`库,也可以使用操作系统的`cron`任务。以下是使用`sched`模块和`schedule`库的两种方法:
使用`sched`模块
```python
import sched
import time
def crawl_task():
这里编写爬虫代码
pass
scheduler = sched.scheduler(time.time, time.sleep)
scheduler.enter(300, 1, crawl_task) 每隔5分钟执行一次
scheduler.run()
使用`schedule`库
```python
import schedule
import time
def job():
这里编写爬虫代码
pass
schedule.every(5).minutes.do(job)
while True:
schedule.run_pending()
time.sleep(1)
使用`cron`任务(Linux系统)
2. 打开`crontab`并添加一行,格式为`* /path/to/script.py`。
3. 设置时间间隔,例如,每天凌晨3点启动爬虫。
4. 保存并退出`crontab`,按`y`确认保存。
例如,要在每天凌晨3点启动爬虫,请在`crontab`文件中添加以下行:
```
0 3 * * * /path/to/script.py
确保替换`/path/to/script.py`为爬虫脚本的实际路径。
选择合适的方法取决于您的具体需求和环境。