136 lines
4.2 KiB
Python
136 lines
4.2 KiB
Python
"""
|
|
2월 데이터 크롤링 스크립트
|
|
5호기(kremc-05), 9호기(nrems-09)의 2월 일별/시간별 데이터를 수집합니다.
|
|
"""
|
|
|
|
import sys
|
|
import os
|
|
import importlib
|
|
from datetime import datetime
|
|
from dotenv import load_dotenv
|
|
|
|
# .env 로드
|
|
load_dotenv()
|
|
|
|
# Windows 인코딩 문제 해결
|
|
if sys.platform.startswith('win'):
|
|
sys.stdout.reconfigure(encoding='utf-8')
|
|
sys.stderr.reconfigure(encoding='utf-8')
|
|
|
|
# 프로젝트 루트 경로 추가
|
|
current_dir = os.path.dirname(os.path.abspath(__file__))
|
|
sys.path.append(current_dir)
|
|
|
|
from config import get_all_plants
|
|
from database import save_history
|
|
|
|
def get_plant_config(target_id):
|
|
"""플랜트 설정 가져오기"""
|
|
plants = get_all_plants()
|
|
for p in plants:
|
|
if p.get('id') == target_id:
|
|
return p
|
|
return None
|
|
|
|
def fetch_february_data(plant_config):
|
|
"""2월 데이터 수집"""
|
|
plant_id = plant_config['id']
|
|
plant_type = plant_config['type']
|
|
plant_name = plant_config['name']
|
|
|
|
print(f"\n{'='*60}")
|
|
print(f"🚀 [{plant_name}] 2월 데이터 수집 시작 ({plant_id})")
|
|
print(f" 타입: {plant_type}")
|
|
print(f"{'='*60}")
|
|
|
|
# 크롤러 모듈 동적 임포트
|
|
try:
|
|
crawler_module = importlib.import_module(f"crawlers.{plant_type}")
|
|
except ImportError:
|
|
print(f"❌ 크롤러 모듈을 찾을 수 없습니다: crawlers/{plant_type}.py")
|
|
return
|
|
|
|
# 2월 데이터 범위 설정
|
|
now = datetime.now()
|
|
year = now.year
|
|
|
|
# 2월 1일부터 오늘까지 (또는 2월 말일까지)
|
|
start_date = f"{year}-02-01"
|
|
# 현재가 2월이면 오늘까지, 3월 이후면 2월 마지막 날까지
|
|
if now.month == 2:
|
|
end_date = now.strftime("%Y-%m-%d")
|
|
else:
|
|
# 2월 마지막 날 (윤년 고려)
|
|
if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
|
|
end_date = f"{year}-02-29"
|
|
else:
|
|
end_date = f"{year}-02-28"
|
|
|
|
print(f"\n📅 수집 기간: {start_date} ~ {end_date}")
|
|
|
|
# 1. 시간별 데이터 수집
|
|
try:
|
|
print(f"\n⏳ [Hourly] 시간별 데이터 수집 중...")
|
|
|
|
if hasattr(crawler_module, 'fetch_history_hourly'):
|
|
hourly_data = crawler_module.fetch_history_hourly(plant_config, start_date, end_date)
|
|
if hourly_data:
|
|
print(f" ✅ {len(hourly_data)}개 시간별 데이터 수집 완료")
|
|
save_history(hourly_data, 'hourly')
|
|
print(f" ✅ DB 저장 완료")
|
|
else:
|
|
print(" ⚠️ 데이터 없음")
|
|
else:
|
|
print(f" ⚠️ {plant_type}는 시간별 이력 수집을 지원하지 않음")
|
|
|
|
except Exception as e:
|
|
print(f"❌ [Hourly] 에러: {e}")
|
|
import traceback
|
|
traceback.print_exc()
|
|
|
|
# 2. 일별 데이터 수집
|
|
try:
|
|
print(f"\n⏳ [Daily] 일별 데이터 수집 중...")
|
|
|
|
if hasattr(crawler_module, 'fetch_history_daily'):
|
|
daily_data = crawler_module.fetch_history_daily(plant_config, start_date, end_date)
|
|
if daily_data:
|
|
print(f" ✅ {len(daily_data)}개 일별 데이터 수집 완료")
|
|
save_history(daily_data, 'daily')
|
|
print(f" ✅ DB 저장 완료")
|
|
else:
|
|
print(" ⚠️ 데이터 없음")
|
|
else:
|
|
print(f" ⚠️ {plant_type}는 일별 이력 수집을 지원하지 않음")
|
|
|
|
except Exception as e:
|
|
print(f"❌ [Daily] 에러: {e}")
|
|
import traceback
|
|
traceback.print_exc()
|
|
|
|
print(f"\n✅ [{plant_name}] 모든 작업 완료\n")
|
|
|
|
def main():
|
|
"""메인 실행 함수"""
|
|
target_plants = ['kremc-05', 'nrems-09'] # 5호기, 9호기
|
|
|
|
print("\n" + "="*60)
|
|
print("🌞 2월 데이터 크롤링 시작")
|
|
print(f"대상: 5호기(kremc-05), 9호기(nrems-09)")
|
|
print("="*60)
|
|
|
|
for plant_id in target_plants:
|
|
cfg = get_plant_config(plant_id)
|
|
|
|
if cfg:
|
|
fetch_february_data(cfg)
|
|
else:
|
|
print(f"❌ 설정을 찾을 수 없습니다: {plant_id}")
|
|
|
|
print("\n" + "="*60)
|
|
print("🎉 모든 작업 완료!")
|
|
print("="*60 + "\n")
|
|
|
|
if __name__ == "__main__":
|
|
main()
|