Profile picture

[Python] PySide6 + Selenium: 앱 종료 시 브라우저도 안전하게 닫기

JaehyoJJAng2024년 08월 15일

들어가며

PySide6와 Selenium을 함께 사용해 GUI 애플리케이션을 만들 때,

앱이 종료되더라도 셀레니움 브라우저가 종료되지 않아 crashed 문제가 발생하는 경우가 있었다.

이번 글에서는 애플리케이션 종료 시 브라우저를 안전하게 닫는 방법에 대해 기록해보려고 한다.


해결 방법

셀레니움 브라우저를 안전하게 종료하기 위한 몇 가지 방법이 있다.

대표적으로 closeEvent 메서드 재정의, atexit 모듈 사용, 멀티스레드 환경에서 안전하게 종료하는 방법을 다뤄보겠다.


closeEvent를 활용한 브라우저 종료

PySide6의 closeEvent 메서드를 재정의하여 애플리케이션 창이 닫힐 때 브라우저도 함께 종료되도록 설정해보자.

아래는 예제 코드이다.

from PySide6.QtWidgets import QApplication, QMainWindow
from selenium import webdriver
import sys

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Selenium GUI")
        self.browser = webdriver.Chrome()  # 셀레니움 브라우저 초기화

    def closeEvent(self, event):
        # 브라우저 종료 코드
        if self.browser:
            self.browser.quit()
        event.accept()  # 창 종료 허용

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec())

위 코드에서는 closeEvent 메서드를 재정의하여 애플리케이션 종료 시 셀레니움 브라우저가 정상 종료되도록 한다.


atexit 모듈을 이용한 자동 종료

atexit 모듈을 사용하면 프로그램 종료 시 자동으로 브라우저를 닫도록 설정할 수 있다.

import atexit
from PySide6.QtWidgets import QApplication, QMainWindow
from selenium import webdriver
import sys

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Selenium GUI")
        self.browser = webdriver.Chrome()
        atexit.register(self.quit_browser)

    def quit_browser(self):
        if self.browser:
            self.browser.quit()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec())

Loading script...