from selenium import webdriver from selenium.webdriver.chrome.service import Service as ChromeService from selenium.webdriver.firefox.service import Service as FirefoxService from selenium.webdriver.edge.service import Service as EdgeService from selenium.webdriver.edge.options import Options as EdgeOptions import os from Config.UIConfig import Config ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) class DriverSelector: def __init__(self, driver_path=ROOT_DIR+Config.EDGE_DRIVER): """ 初始化驱动器选择器,默认选择Edge :param driver_path: 默认的驱动地址 """ self.driver_path = driver_path self.driver = None # 检查驱动文件是否存在 if not os.path.exists(self.driver_path): raise FileNotFoundError(f"驱动程序未找到: {self.driver_path}") def create_chrome_driver(self, options=None): if options is None: options = webdriver.ChromeOptions() options.add_argument('--start-maximized') options.add_argument('--disable-notifications') service = ChromeService(executable_path=self.driver_path) self.driver = webdriver.Chrome(service=service, options=options) return self.driver def create_firefox_driver(self, options=None): if options is None: options = webdriver.FirefoxOptions() options.add_argument('--start-maximized') service = FirefoxService(executable_path=self.driver_path) self.driver = webdriver.Firefox(service=service, options=options) return self.driver def create_edge_driver(self, options=None): if options is None: print(self.driver_path) options = EdgeOptions() options.add_argument('--start-maximized') options.add_argument('--disable-notifications') # 添加使用Chromium版本的Edge标志 options.use_chromium = True service = EdgeService(executable_path=self.driver_path) self.driver = webdriver.Edge(service=service, options=options) return self.driver def close_driver(self): if self.driver: self.driver.quit() self.driver = None def get_driver_info(self): if self.driver: return { "browser_name": self.driver.name, "browser_version": self.driver.capabilities['browserVersion'], "driver_path": self.driver_path } return None # 示例 if __name__ == "__main__": # 创建驱动选择器实例 selector = DriverSelector() try: # 创建Edge驱动 driver = selector.create_edge_driver() # 打开网页 driver.get("https://www.baidu.com") print("当前页面标题:", driver.title) # 获取驱动信息 info = selector.get_driver_info() print("浏览器信息:", info) except Exception as e: print(f"发生错误: {e}") finally: # 关闭驱动 if 'selector' in locals(): selector.close_driver()