Files
fg-auto/data/weather_capture.py
2025-06-27 11:55:21 +09:00

78 lines
2.5 KiB
Python

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from datetime import datetime
import os
import time
import tempfile
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = Options()
options.add_argument('--headless')
options.add_argument('--window-size=1802,1467')
# 임시 폴더 생성 후 user-data-dir로 지정 (매 실행마다 새 폴더 사용)
temp_dir = tempfile.mkdtemp()
options.add_argument(f'--user-data-dir={temp_dir}')
# Docker에서 권장하는 옵션
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
driver = webdriver.Chrome(options=options)
# 현재 스크립트 경로 기준 저장
script_dir = os.path.dirname(os.path.abspath(__file__))
# 브라우저 옵션 설정
options = Options()
options.add_argument('--headless')
options.add_argument('--window-size=1802,1467')
driver = webdriver.Chrome(options=options)
driver.get('https://www.weather.go.kr/w/weather/forecast/short-term.do#dong/4148026200/37.73208578534846/126.79463099866948')
wait = WebDriverWait(driver, 10)
# 첫 번째 탭 클릭 (안전하게 element_to_be_clickable 사용)
tab_button = wait.until(EC.element_to_be_clickable(
(By.XPATH, '//*[@id="digital-forecast"]/div[1]/div[3]/div[1]/div/div/a[2]')
))
tab_button.click()
# 두 번째 항목 클릭 (stale element 대비해서 클릭 직전 다시 찾기)
list_button_xpath = '//*[@id="digital-forecast"]/div[1]/div[3]/ul/div[1]/a[2]'
for attempt in range(3): # 최대 3번 재시도
try:
list_button = wait.until(EC.element_to_be_clickable((By.XPATH, list_button_xpath)))
list_button.click()
break
except Exception as e:
print(f"시도 {attempt+1}: 오류 발생 - {e}. 재시도 중...")
time.sleep(1)
else:
print("요소 클릭 실패. 스크립트 종료.")
driver.quit()
exit(1)
time.sleep(2) # 클릭 후 페이지 반영 대기
# 캡처 대상 요소 찾기
target_element = wait.until(EC.presence_of_element_located(
(By.XPATH, '/html/body/div[2]/section/div/div[2]')
))
# 파일 저장 경로 설정
timestamp = datetime.now().strftime('%Y%m%d')
save_path = os.path.join(script_dir, f'weather_capture_{timestamp}.png')
# 요소 스크린샷 저장
target_element.screenshot(save_path)
driver.quit()
print(f'📸 캡처 완료! 저장 위치: {save_path}')