1
1
mirror of https://github.com/KenanZhu/AutoLibrary.git synced 2026-06-17 23:13:03 +08:00

refactor: LoginPage 继承 MsgBase,统一页面消息追踪机制

This commit is contained in:
2026-06-13 08:59:34 +08:00
parent 609850ab60
commit 72301c63fd
2 changed files with 28 additions and 32 deletions
+15 -13
View File
@@ -10,6 +10,7 @@ See the LICENSE file for details.
import os import os
import queue import queue
from selenium import webdriver from selenium import webdriver
from selenium.webdriver.remote.webdriver import WebDriver
from selenium.common.exceptions import ( from selenium.common.exceptions import (
TimeoutException, TimeoutException,
WebDriverException, WebDriverException,
@@ -37,11 +38,11 @@ class AutoLib(MsgBase):
output_queue: queue.Queue, output_queue: queue.Queue,
run_config: dict, run_config: dict,
) -> None: ) -> None:
super().__init__(input_queue, output_queue)
super().__init__(input_queue, output_queue)
self.__run_config: dict = run_config self.__run_config: dict = run_config
self.__user_config: dict | None = None self.__user_config: dict | None = None
self.__driver = None self.__driver: WebDriver | None = None
self.__driver_type: str = "" self.__driver_type: str = ""
self.__driver_path: str = "" self.__driver_path: str = ""
self.__login_page: LoginPage = None self.__login_page: LoginPage = None
@@ -58,7 +59,7 @@ class AutoLib(MsgBase):
else: else:
if not self.__initDriverUrl(): if not self.__initDriverUrl():
self.close() self.close()
raise Exception("浏览器驱动URL初始化失败 !") raise Exception("浏览器驱动 URL 初始化失败 !")
self.__initPagesServices() self.__initPagesServices()
self.__initPagesFlows() self.__initPagesFlows()
@@ -67,9 +68,10 @@ class AutoLib(MsgBase):
) -> bool: ) -> bool:
self._showTrace("正在初始化浏览器驱动......", no_log=True) self._showTrace("正在初始化浏览器驱动......", no_log=True)
web_driver_config: dict = self.__run_config.get("web_driver", None) driver_config: dict = self.__run_config.get("web_driver", None)
self.__driver_type = web_driver_config.get("driver_type", "none") self.__driver_type = driver_config.get("driver_type", "none")
match self.__driver_type.lower(): self.__driver_type = self.__driver_type.lower()
match self.__driver_type:
case "edge": case "edge":
driver_options = webdriver.EdgeOptions() driver_options = webdriver.EdgeOptions()
case "chrome": case "chrome":
@@ -82,10 +84,10 @@ class AutoLib(MsgBase):
self.TraceLevel.WARNING, self.TraceLevel.WARNING,
) )
return False return False
if not web_driver_config: if not driver_config:
self._showTrace("未配置浏览器驱动参数 !", self.TraceLevel.ERROR) self._showTrace("未配置浏览器驱动参数 !", self.TraceLevel.ERROR)
return False return False
if web_driver_config.get("headless", False): if driver_config.get("headless", False):
driver_options.add_argument("--headless") driver_options.add_argument("--headless")
driver_options.add_argument("--disable-gpu") driver_options.add_argument("--disable-gpu")
driver_options.add_argument("--no-sandbox") driver_options.add_argument("--no-sandbox")
@@ -110,11 +112,11 @@ class AutoLib(MsgBase):
"AppleWebKit/537.36 (KHTML, like Gecko) "\ "AppleWebKit/537.36 (KHTML, like Gecko) "\
"Chrome/120.0.0.0 "\ "Chrome/120.0.0.0 "\
"Safari/537.36" "Safari/537.36"
if self.__driver_type.lower() == "edge": if self.__driver_type == "edge":
user_agent += " Edg/120.0.0.0" user_agent += " Edg/120.0.0.0"
# set options for firefox # set options for firefox
elif self.__driver_type.lower() == "firefox": elif self.__driver_type == "firefox":
driver_options.set_preference("dom.webdriver.enabled", False) driver_options.set_preference("dom.webdriver.enabled", False)
driver_options.set_preference("useAutomationExtension", False) driver_options.set_preference("useAutomationExtension", False)
user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:120.0) "\ user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:120.0) "\
@@ -122,14 +124,14 @@ class AutoLib(MsgBase):
driver_options.add_argument(f"user-agent={user_agent}") driver_options.add_argument(f"user-agent={user_agent}")
# init browser driver # init browser driver
self.__driver_path = web_driver_config.get("driver_path", "") self.__driver_path = driver_config.get("driver_path", "")
if not self.__driver_path: if not self.__driver_path:
self._showTrace("未配置浏览器驱动路径 !", self.TraceLevel.WARNING) self._showTrace("未配置浏览器驱动路径 !", self.TraceLevel.WARNING)
return False return False
try: try:
self.__driver_path = os.path.abspath(self.__driver_path) self.__driver_path = os.path.abspath(self.__driver_path)
service = None service = None
match self.__driver_type.lower(): match self.__driver_type:
case "edge": case "edge":
service = EdgeService(executable_path=self.__driver_path) service = EdgeService(executable_path=self.__driver_path)
self.__driver = webdriver.Edge(service=service, options=driver_options) self.__driver = webdriver.Edge(service=service, options=driver_options)
@@ -161,7 +163,7 @@ class AutoLib(MsgBase):
self._showTrace("未配置图书馆参数 !", self.TraceLevel.ERROR) self._showTrace("未配置图书馆参数 !", self.TraceLevel.ERROR)
return False return False
url: str = lib_config.get("host_url") + lib_config.get("login_url") url: str = lib_config.get("host_url") + lib_config.get("login_url")
self.__login_page = LoginPage(self.__driver, tracer=self._showTrace) self.__login_page = LoginPage(self._input_queue, self._output_queue, self.__driver)
self.__driver.set_page_load_timeout(5) self.__driver.set_page_load_timeout(5)
try: try:
self.__driver.get(url) self.__driver.get(url)
+13 -19
View File
@@ -7,7 +7,8 @@ This software is provided "as is", without any warranty of any kind.
You may use, modify, and distribute this file under the terms of the MIT License. You may use, modify, and distribute this file under the terms of the MIT License.
See the LICENSE file for details. See the LICENSE file for details.
""" """
from typing import Callable, Optional import queue
from typing import Callable
from selenium.common.exceptions import ( from selenium.common.exceptions import (
ElementNotInteractableException, ElementNotInteractableException,
@@ -19,8 +20,10 @@ from selenium.webdriver.remote.webdriver import WebDriver
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support import expected_conditions as EC
from base.MsgBase import MsgBase
class LoginPage:
class LoginPage(MsgBase):
USERNAME_INPUT = (By.NAME, "username") USERNAME_INPUT = (By.NAME, "username")
PASSWORD_INPUT = (By.NAME, "password") PASSWORD_INPUT = (By.NAME, "password")
@@ -36,22 +39,13 @@ class LoginPage:
def __init__( def __init__(
self, self,
input_queue: queue.Queue,
output_queue: queue.Queue,
driver: WebDriver, driver: WebDriver,
tracer: Optional[Callable[..., None]] = None,
) -> None: ) -> None:
super().__init__(input_queue, output_queue)
self._driver: WebDriver = driver self._driver: WebDriver = driver
self._tracer: Optional[Callable[..., None]] = tracer
def _trace(
self,
msg: str,
level: int = 20,
no_log: bool = False,
) -> None:
if self._tracer:
self._tracer(msg, level, no_log)
def navigate( def navigate(
self, self,
@@ -185,7 +179,7 @@ class LoginPage:
) -> bool: ) -> bool:
for attempt in range(max_attempts): for attempt in range(max_attempts):
self._trace( self._showTrace(
f"用户 {username}{attempt + 1} 次尝试登录......", f"用户 {username}{attempt + 1} 次尝试登录......",
no_log=True, no_log=True,
) )
@@ -196,16 +190,16 @@ class LoginPage:
continue continue
if not self.fillCaptcha(captcha_text): if not self.fillCaptcha(captcha_text):
continue continue
self._trace("尝试登录...", no_log=True) self._showTrace("尝试登录...", no_log=True)
if not self.clickLogin(): if not self.clickLogin():
continue continue
if self.waitLoginSuccess(): if self.waitLoginSuccess():
self._trace(f"用户 {username}{attempt + 1} 次登录成功 !") self._showTrace(f"用户 {username}{attempt + 1} 次登录成功 !")
return True return True
else: else:
self._trace( self._showTrace(
"登录页面加载失败 ! : " "登录页面加载失败 ! : "
"用户账号或者密码错误/验证码错误, 具体以页面提示为准", "用户账号或者密码错误/验证码错误, 具体以页面提示为准",
level=40, level=self.TraceLevel.ERROR,
) )
return False return False