Selenium 4.9版本更新后Edge浏览器IE模式无法正常运行
Selenium 4.9版本更新后Edge浏览器IE模式无法正常运行
我太懂你这种升级后脚本突然崩了的烦躁了!升级到Selenium 4.9之后,原本正常跑的Edge IE模式脚本直接报错,提示浏览器类型无效,对吧?咱们来一步步拆解问题、解决它。
问题根源分析
你之前用webdriver.Ie()来配置Edge的IE模式,在Selenium 4.9之前可能还能凑合用,但新版本的Selenium Manager(Selenium自带的驱动管理工具)对浏览器类型的校验变得更严格了——它不认这种用IE驱动去连接Edge的操作逻辑,所以才抛出了internet explorer is not a valid browser的错误。
另外你代码里还有个容易忽略的小问题:你是先创建了driver实例,之后才添加useAutomationExtension和excludeSwitches这两个选项,这完全没用!这些配置必须在初始化driver之前设置好,不然根本不会生效。
修正后的完整代码
咱们直接调整核心逻辑:改用Edge驱动来配置IE模式,把所有选项配置移到创建driver之前,代码如下:
import time from selenium import webdriver # 改用EdgeOptions来配置IE模式,替代原来的IeOptions edge_options = webdriver.EdgeOptions() edge_options.attach_to_edge_chrome = True edge_options.edge_executable_path = "C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe" # 把自动化相关选项移到创建driver之前,确保配置生效 edge_options.add_additional_option("useAutomationExtension", False) edge_options.add_additional_option("excludeSwitches", ['enable-automation']) # 用Edge驱动初始化实例,替代原来的webdriver.Ie() driver = webdriver.Edge(options=edge_options) username1 = "admin" password1 = "admin123" driver.maximize_window() links = ["http://web1.com", "http://web2.com", "http://web3.com"] count = 1 for link in links: time.sleep(1) driver.get(link) windows_before = driver.current_window_handle elem1 = driver.find_element("id", "username").send_keys(username1) elem2 = driver.find_element("id", "password").send_keys(password1) time.sleep(1) if count == 1: driver.execute_script('document.title = "web1"') elif count == 2: driver.execute_script('document.title = "web2"') else: driver.execute_script('document.title = "web3"') if count == 3: break driver.execute_script("window.open('');") new_window = driver.window_handles[count] count += 1 driver.switch_to.window(new_window)
额外注意事项
- 确保你的Edge浏览器版本和Selenium 4.9兼容,建议把Edge升级到最新稳定版;
- 如果你之前手动下载过IEDriverServer,要确保它的版本和Edge版本匹配,并且放在系统PATH里(不过Selenium 4+的Selenium Manager会自动下载匹配的驱动,一般不需要手动处理);
- 运行脚本前,关闭所有打开的Edge窗口,避免驱动连接冲突。
备注:内容来源于stack exchange,提问作者Mohamed Hussein
相关产品推荐
相关产品推荐

