diff --git a/test/s_gpt.py b/test/s_gpt.py new file mode 100644 index 00000000..e35e65c4 --- /dev/null +++ b/test/s_gpt.py @@ -0,0 +1,133 @@ +import sys +import asyncio +from PySide6.QtWidgets import (QApplication, QWidget, QVBoxLayout, QPushButton, QLineEdit, QCheckBox, QTextEdit, QLabel) +from PySide6.QtCore import Qt +from PySide6.QtGui import QTextCursor +from playwright.async_api import async_playwright +import qasync + +class WebAutomationApp(QWidget): + def __init__(self): + super().__init__() + self.browser = None # 브라우저 객체를 저장할 변수 + self.page = None # 페이지 객체를 저장할 변수 + self.playwright_context = None # Playwright 컨텍스트 유지 + self.initUI() + + def initUI(self): + self.setWindowTitle('Web Automation with Playwright') + + # 레이아웃 설정 + layout = QVBoxLayout() + + # 입력창 + self.url_input = QLineEdit(self) + self.url_input.setPlaceholderText("URL을 입력하세요 (예: https://www.naver.com)") + layout.addWidget(QLabel("URL 입력:")) + layout.addWidget(self.url_input) + + # 로그 출력 창 + self.log_output = QTextEdit(self) + self.log_output.setReadOnly(True) + layout.addWidget(QLabel("로그 출력:")) + layout.addWidget(self.log_output) + + # 네이버 연결 버튼 + self.start_button = QPushButton("네이버 열기", self) + self.start_button.clicked.connect(self.on_start_button_click) + layout.addWidget(self.start_button) + + # 다음 페이지 이동 버튼 + self.daum_button = QPushButton("다음 페이지로 이동", self) + self.daum_button.clicked.connect(self.on_daum_button_click) + layout.addWidget(self.daum_button) + + # 브라우저 닫기 버튼 + self.close_browser_button = QPushButton("브라우저 닫기", self) + self.close_browser_button.clicked.connect(self.on_close_browser_click) + layout.addWidget(self.close_browser_button) + + # 종료 버튼 + self.exit_button = QPushButton("종료", self) + self.exit_button.clicked.connect(self.close_app) + layout.addWidget(self.exit_button) + + self.setLayout(layout) + + async def open_naver(self, url): + # Playwright를 이용해 네이버 웹페이지 열기 + self.playwright_context = await async_playwright().start() + self.log_message("Playwright 시작 중...") + self.browser = await self.playwright_context.chromium.launch(headless=False) + self.page = await self.browser.new_page() + await self.page.goto(url) + self.log_message(f"{url} 로 이동 중...") + + def log_message(self, message): + self.log_output.append(message) + self.log_output.moveCursor(QTextCursor.End) + + def on_start_button_click(self): + url = self.url_input.text() + if url == "": + self.log_message("URL을 입력하세요.") + return + + # 비동기 작업 시작 + self.log_message(f"{url} 연결 시도 중...") + asyncio.ensure_future(self.start_playwright_task(url)) + + async def start_playwright_task(self, url): + try: + await self.open_naver(url) + except Exception as e: + self.log_message(f"오류 발생: {e}") + + def on_daum_button_click(self): + # 사용자가 '다음 페이지로 이동' 버튼을 눌렀을 때 동작 + asyncio.ensure_future(self.navigate_to_daum()) + + async def navigate_to_daum(self): + if self.page: + self.log_message("다음 페이지로 이동 중...") + await self.page.goto("https://www.daum.net") + self.log_message("다음 페이지로 이동 완료.") + else: + self.log_message("열려 있는 브라우저가 없습니다.") + + async def close_browser(self): + if self.browser: + await self.browser.close() + await self.playwright_context.stop() + self.log_message("브라우저 닫힘") + self.browser = None + else: + self.log_message("열려 있는 브라우저가 없습니다.") + + def on_close_browser_click(self): + asyncio.ensure_future(self.close_browser()) + + def close_app(self): + self.log_message("프로그램 종료 중...") + asyncio.ensure_future(self.close_browser()) # 프로그램 종료 전 브라우저 닫기 + self.close() # 윈도우 닫기 + +async def main(): + app = QApplication(sys.argv) + loop = qasync.QEventLoop(app) # qasync를 이용한 이벤트 루프 통합 + asyncio.set_event_loop(loop) # asyncio 이벤트 루프 설정 + + main_window = WebAutomationApp() + main_window.show() + + with loop: # 이벤트 루프 시작 + try: + loop.run_forever() # 이벤트 루프를 종료하지 않고 계속 유지 + except (KeyboardInterrupt, SystemExit): + print("이벤트 루프 종료 중...") + +if __name__ == "__main__": + if sys.platform == "win32": + asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) # Windows에서 SelectorEventLoop 사용 설정 + + asyncio.run(main()) diff --git a/test/sample.py b/test/sample.py new file mode 100644 index 00000000..ed8b5d3d --- /dev/null +++ b/test/sample.py @@ -0,0 +1,98 @@ +import asyncio +import sys +from playwright.async_api import async_playwright, Browser, BrowserContext, Page +from PySide6.QtCore import Qt, QObject, QRunnable, QThreadPool, Signal +from PySide6.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, + QLabel, QLineEdit, QPushButton, QCheckBox, QTextEdit) + +class PlaywrightWorker(QObject, QRunnable): + finished = Signal(str) + + def __init__(self, url): + super().__init__() + self.url = url + self.setAutoDelete(True) + + def run(self): + try: + asyncio.set_event_loop(asyncio.new_event_loop()) # 중요: 새로운 이벤트 루프 설정 + loop = asyncio.get_event_loop() + loop.run_until_complete(self.run_playwright()) # loop 인자 제거 + loop.close() + except Exception as e: + print(f"PlaywrightWorker Error: {e}") # 에러 자세히 출력 + self.finished.emit(str(e)) + + async def run_playwright(self): + async with async_playwright() as p: + browser: Browser = await p.chromium.launch(headless=False) + context: BrowserContext = await browser.new_context() + page: Page = await context.new_page() + try: + await page.goto(self.url) + print("Page navigation successful!") # 성공 메시지 출력 + except Exception as e: + print(f"Page navigation failed: {e}") # 에러 자세히 출력 + raise # 예외를 다시 발생시켜 상위에서 처리 + finally: + await asyncio.gather(page.close(), context.close(), browser.close()) + print("Browser closed successfully!") # 성공 메시지 출력 + +class MainWindow(QMainWindow): + def __init__(self): + super().__init__() + self.setWindowTitle("Playwright Web Automation") + self.threadpool = QThreadPool() + self.create_layout() + + def create_layout(self): + # Input fields + url_label = QLabel("URL:") + self.url_input = QLineEdit() + self.url_input.setText("https://www.naver.com") #Default URL + + # Button + self.go_button = QPushButton("Go") + self.go_button.clicked.connect(self.start_playwright) + + # Log output + self.log_output = QTextEdit() + self.log_output.setReadOnly(True) + + + # Layout + main_layout = QVBoxLayout() + main_layout.addWidget(url_label) + main_layout.addWidget(self.url_input) + main_layout.addWidget(self.go_button) + main_layout.addWidget(self.log_output) + + + central_widget = QWidget() + central_widget.setLayout(main_layout) + self.setCentralWidget(central_widget) + + + def start_playwright(self): + url = self.url_input.text() + worker = PlaywrightWorker(url) + worker.finished.connect(self.on_playwright_finished) + self.threadpool.start(worker) + + def on_playwright_finished(self, error_message=""): + if error_message: + self.log_output.append(f"Error: {error_message}") # 에러 메시지 자세히 출력 + else: + self.log_output.append("Playwright task finished successfully.") + + def closeEvent(self, event): + self.threadpool.waitForDone() + self.log_output.append("Application closing...") + event.accept() + + +if __name__ == "__main__": + app = QApplication(sys.argv) + window = MainWindow() + window.show() + sys.exit(app.exec())