AP_Browser/wh_con.py

144 lines
6.4 KiB
Python

import os, sys
from pywinauto import Application, findwindows
from pywinauto.controls.hwndwrapper import HwndWrapper
from pywinauto import Application, findwindows, timings
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from PySide6.QtCore import Qt, Signal, Slot, QRect, QSettings, QTimer
import time
from src.loggerModule import Logger
import logging
class WhaleController:
def __init__(self):
self.logger = Logger(log_file="app.log", logger_name="App_Logger", level=logging.DEBUG)
self.logger.log(f"로그기록이 설정되었습니다.", level=logging.INFO)
self.driver = None
self.browser_pid = None
self.whale_window = None
def find_whale(self):
"""pywinauto를 사용하여 웨일 브라우저 제어"""
try:
if not self.browser_pid:
self.logger.log("브라우저 PID를 찾을 수 없습니다. 먼저 Selenium으로 실행해야 합니다.")
return
# 최대 10초 동안 '새 시크릿 탭 - Whale' 창이 나타나기를 기다림
timings.wait_until(10, 0.5, lambda: any(window.name == 'whale://new-tab-page-third-party/ - Whale' for window in findwindows.find_elements()))
windows = findwindows.find_elements()
for window in windows:
if "whale" in window.name.lower() or window.process_id == self.browser_pid:
self.logger.log(f"찾은 창: {window.name}, PID: {window.process_id}")
if window.name == 'whale://new-tab-page-third-party/ - Whale':
self.logger.log("웨일 브라우저를 찾았음 - whale://new-tab-page-third-party/ - Whale", level=logging.INFO)
# pywinauto로 PID를 기반으로 애플리케이션에 연결
whale_app = Application(backend="uia").connect(process=window.process_id)
self.whale_window = whale_app.top_window()
# 창 위치 및 크기 조정
hwnd_wrapper = HwndWrapper(self.whale_window.handle)
hwnd_wrapper.move_window(x=1, y=1, width=1280, height=720)
self.whale_window.set_focus()
except Exception as e:
self.logger.log(f"웨일 제어 중 오류 발생: {e}", level=logging.ERROR, exc_info=True)
def get_base_dir(self):
"""
실행 환경에 따라 base_dir을 설정하는 메서드.
cx_Freeze로 패키징된 경우 실행 파일의 경로, 일반 Python 환경일 경우 __file__을 기준으로 설정.
"""
if getattr(sys, 'frozen', False): # 패키징된 경우
base_dir = os.path.dirname(sys.executable)
internal_dir = os.path.join(base_dir, '_internal') # _internal 디렉토리 포함
if os.path.exists(internal_dir): # _internal 디렉토리가 존재하면 base_dir로 설정
return internal_dir
else: # 일반 Python 실행 환경
base_dir = os.path.dirname(os.path.abspath(__file__))
return base_dir
def start_whale_Browser(self):
"""웨일 제어"""
try:
base_path = self.get_base_dir()
whale_exe_path = os.path.join(base_path, "browsers", "whale", "whale.exe")
user_data_dir = os.path.join(base_path, "browsers", "whale", "user_data")
cache_dir = os.path.join(base_path, "browsers", "whale", "cache")
extension_path = os.path.join(base_path, "browsers", "whale", "extensions", "gadfmnjdnhkncfcibhfleoojcdimdcbd", "1.1.11_0")
# Selenium WebDriver 설정
# chromedriver_path = r"./chromedriver_130.0.6723.31.exe"
# chromedriver_path = r"./chromedriver_128.0.6613.137.exe"
chromedriver_path = os.path.join(base_path, "browsers", "chromedriver_128.0.6613.137.exe")
chrome_service = Service(chromedriver_path)
chrome_options = Options()
# chrome_options.add_argument("--headless")
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("--disable-dev-shm-usage")
chrome_options.add_argument("--remote-debugging-port=9222")
chrome_options.add_argument(f"--user-data-dir={user_data_dir}") # 사용자 데이터 폴더 설정
chrome_options.add_argument(f"--disk-cache-dir={cache_dir}") # 캐시 폴더 설정
chrome_options.add_argument(f"--load-extension={extension_path}") # 확장 프로그램 로드
# chrome_options.binary_location = "C:\\Program Files\\Naver\\Naver Whale\\Application\\whale.exe"
chrome_options.binary_location = whale_exe_path
# 사용자 에이전트 설정
chrome_options.add_argument(
"user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/130.0.0.0 Whale/4.29.282.14 Safari/537.36"
)
# 브라우저 실행
self.driver = webdriver.Chrome(service=chrome_service, options=chrome_options)
# self.driver.get("whale://newtab")
# 페이지 로드 대기
time.sleep(0.2)
# Selenium에서 PID 가져오기
self.browser_pid = self.driver.service.process.pid
self.logger.log(f"웨일 브라우저 PID: {self.browser_pid}", level=logging.INFO)
self.find_whale()
# return whale_window, self.driver
except Exception as e:
self.logger.log(f"웨일 브라우저 시작 중 오류 발생: {e}", level=logging.ERROR, exc_info=True)
def close_whale_br(self):
# 브라우저 종료
try:
self.logger.log(f"브라우저를 종료합니다.", level=logging.DEBUG)
if self.driver:
self.driver.quit()
else:
self.logger.log(f"브라우저 객체를 찾을 수 없습니다.", level=logging.WARNING)
except Exception as e:
self.logger.log(f"브라우저 종료 중 오류 발생: {e}", level=logging.ERROR, exc_info=True)
if __name__ == "__main__":
# 웨일 브라우저 컨트롤러 인스턴스 생성
whale_controller = WhaleController()
results = whale_controller.start_whale_Browser()