在Python爬虫中设置时间可以通过以下几种方法:
1. 使用`time.sleep(seconds)`函数:
```python
import time
time.sleep(1) 暂停1秒
2. 使用`threading.Timer(interval, function)`创建定时器:
```python
import threading
def my_function():
你的任务代码
pass
timer = threading.Timer(5, my_function)
timer.start() 在5秒后执行my_function
3. 使用`sched.scheduler(timefunc, delayfunc)`创建事件调度器:
```python
import sched
def crawl_task():
你的任务代码
pass
scheduler = sched.scheduler(time.time, time.sleep)
scheduler.enter(300, 1, crawl_task) 每隔300秒执行一次crawl_task
scheduler.run() 开始调度器
4. 使用`requests`库中的`timeout`参数设置请求超时时间:
```python
import requests
response = requests.get('https://example.com', timeout=3.0) 等待最多3秒
5. 使用`Scrapy`框架的`download_delay`属性设置下载延迟:
```python
class MySpider(scrapy.Spider):
download_delay = 5 设置下载延迟为5秒
6. 使用`random`库随机设置延时:
```python
import random
time.sleep(random.uniform(1, 5)) 随机等待1到5秒
7. 使用`APScheduler`库设置定时任务:
```python
from apscheduler.schedulers.blocking import BlockingScheduler
def run_spider():
你的任务代码
pass
sched = BlockingScheduler()
sched.add_job(run_spider, 'cron', hour=10, minute=15) 每天10点15分执行一次
sched.start() 开始调度器
8. 使用`crontab`在特定时间段自动启动Python爬虫:
```
0 3 * * * /path/to/script.py 每天凌晨3点执行script.py
请根据你的需求选择合适的方法来设置时间