정보통신기술(ICT)

맵 타임랩스 소프트웨어(10.29.24)

해머슴 2024. 10. 29. 11:36
import sys
import os
import time
import cv2
import numpy as np
import requests
import subprocess
import platform
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException, NoSuchElementException, ElementClickInterceptedException
from webdriver_manager.chrome import ChromeDriverManager
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton, QFileDialog, QLabel, QLineEdit
from PyQt5.QtCore import Qt

def apply_shading(image, alpha=1.0, beta=50):
    return cv2.convertScaleAbs(image, alpha=alpha, beta=beta)

def download_images(map_url, address, save_folder, start_year=2020, end_year=2024):
    driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
    driver.get(map_url)

    image_files = []  # 함수 시작 시 image_files 초기화

    try:
        # 주소 입력 후 검색
        print("Trying to locate search box...")
        search_box = WebDriverWait(driver, 15).until(
            EC.presence_of_element_located((By.ID, "search.keyword.query"))
        )
        search_box.clear()
        search_box.send_keys(address)
        search_box.send_keys(Keys.RETURN)
        print("Search box found and address entered.")

        # 검색 결과 대기 (첫 번째 검색 결과가 표시될 때까지 기다림)
        print("Waiting for search results...")
        WebDriverWait(driver, 15).until(
            EC.presence_of_element_located((By.CLASS_NAME, "placelist"))
        )
        time.sleep(2)  # 추가 대기 시간
        print("Search results loaded.")

        # 팝업 레이어가 있을 경우 닫기
        try:
            dimmed_layer = driver.find_element(By.ID, "dimmedLayer")
            driver.execute_script("arguments[0].style.display = 'none';", dimmed_layer)
            print("dimmedLayer closed")
        except NoSuchElementException:
            print("No dimmedLayer found")

        # 스카이뷰 버튼 대기 후 클릭
        print("Locating Skyview button...")
        skyview_button = WebDriverWait(driver, 15).until(
            EC.element_to_be_clickable((By.XPATH, "//a[contains(text(), '스카이뷰')]"))
        )
        skyview_button.click()
        time.sleep(5)  # 스카이뷰 전환 후 대기 (충분히 대기)

        # 연도별 이미지 다운로드
        for year in range(start_year, end_year + 1):
            try:
                print(f"Locating button for year {year}...")
                # 연도별 버튼 CSS 선택자 사용
                year_button_selector = f"button[aria-label*='{year}']"
                year_button = WebDriverWait(driver, 10).until(
                    EC.element_to_be_clickable((By.CSS_SELECTOR, year_button_selector))
                )
                year_button.click()
                time.sleep(2)
                print(f"Year {year} button clicked.")
               
                # 이미지 URL 가져오기
                img = driver.find_element(By.CSS_SELECTOR, ".map_image_selector")
                img_url = img.get_attribute("src")
                img_data = requests.get(img_url).content
                img_path = os.path.join(save_folder, f"{address}_{year}.png")
                with open(img_path, "wb") as file:
                    file.write(img_data)
                image_files.append(img_path)
                print(f"Saved {year} image to {img_path}")
            except TimeoutException:
                print(f"Year {year} button not found or not clickable.")
            except Exception as e:
                print(f"Error downloading {year} image: {e}")

    except TimeoutException:
        print("Failed to load the search box or search results.")
    finally:
        driver.quit()

    return image_files

class SatelliteMapVideoApp(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Satellite Map Image Downloader")
        self.setGeometry(100, 100, 800, 600)

        layout = QVBoxLayout()
        self.label = QLabel("Enter the map URL and address to download images", self)
        self.label.setAlignment(Qt.AlignCenter)
        layout.addWidget(self.label)

        # 지도 URL 입력창
        self.map_url_input = QLineEdit(self)
        self.map_url_input.setPlaceholderText("Enter the map URL here (e.g., https://map.kakao.com/)")
        layout.addWidget(self.map_url_input)

        # 주소 입력창
        self.address_input = QLineEdit(self)
        self.address_input.setPlaceholderText("Enter the address here (e.g., 부산광역시 기장군 기장읍 내리길 143-14)")
        layout.addWidget(self.address_input)

        # 다운로드 버튼
        self.download_button = QPushButton("Download Skyview Images", self)
        self.download_button.clicked.connect(self.download_images)
        layout.addWidget(self.download_button)

        self.setLayout(layout)

    def download_images(self):
        map_url = self.map_url_input.text().strip()
        address = self.address_input.text().strip()
       
        if not map_url or not address:
            self.label.setText("Please enter both the map URL and address.")
            return

        save_folder = os.path.join(os.getcwd(), "downloaded_maps")
        os.makedirs(save_folder, exist_ok=True)

        image_files = download_images(map_url, address, save_folder)
        if image_files:
            self.label.setText(f"{len(image_files)} images downloaded.")
        else:
            self.label.setText("Failed to download images. Please check the map URL and address.")

def main():
    app = QApplication(sys.argv)
    window = SatelliteMapVideoApp()
    window.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()

 

 

https://www.tistory.com/event/write-challenge-2024

 

작심삼주 오블완 챌린지

오늘 블로그 완료! 21일 동안 매일 블로그에 글 쓰고 글력을 키워보세요.

www.tistory.com