在C#的Selenium测试执行中,能否显示Microsoft Edge中的MS账户列表?
如何在Selenium测试中显示Edge浏览器的Microsoft账户列表
完全可以实现,以下是两种可行的方案:
方案1:通过Edge设置页面定位元素提取账户列表
这种方法模拟用户访问设置页面的操作,直接抓取页面上的账户信息:
- 加载包含账户的用户配置文件
Selenium默认使用临时空白配置文件,必须指定你存储账户信息的Edge用户数据目录,才能让浏览器加载已保存的账户:
from selenium import webdriver from selenium.webdriver.edge.options import Options edge_options = Options() # 替换为你的Edge用户数据实际路径,Windows默认路径示例如下 edge_options.add_argument(r"user-data-dir=C:\Users\你的用户名\AppData\Local\Microsoft\Edge\User Data") # 若有多个配置文件,可指定具体的Profile,比如Profile 1 edge_options.add_argument(r"profile-directory=Profile 1") driver = webdriver.Edge(options=edge_options)
- 访问Edge账户设置页面
driver.get("edge://settings/profiles")
- 定位并提取账户信息
根据Edge设置页面的DOM结构,定位账户元素并提取名称、邮箱等信息(选择器需根据Edge版本调整,以下为通用示例):
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By wait = WebDriverWait(driver, 10) # 等待账户列表加载完成 account_items = wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, 'div[class*="profile-item-container"]'))) # 遍历输出账户信息 for item in account_items: try: account_name = item.find_element(By.CSS_SELECTOR, 'span[class*="profile-name"]').text account_email = item.find_element(By.CSS_SELECTOR, 'span[class*="profile-subtitle"]').text print(f"账户:{account_name} ({account_email})") except Exception as e: print(f"提取账户信息失败:{str(e)}")
方案2:利用Edge DevTools Protocol(CDP)直接获取账户数据
通过CDP命令可以无需访问设置页面,直接从浏览器内核获取账户关联的配置文件信息:
# 启动driver后,调用CDP的Browser.getProfiles命令 profiles = driver.execute_cdp_cmd("Browser.getProfiles", {}) # 解析返回的配置数据(包含账户关联信息) for profile in profiles.get("profiles", []): print(f"账户名称:{profile.get('name', '未知')}") print(f"关联邮箱:{profile.get('userName', '未绑定')}") print(f"配置文件路径:{profile.get('path', '未知')}") print("---")
注意事项
- 必须确保指定的用户数据目录有读写权限,且启动Edge时没有其他实例占用该目录。
- Edge设置页面的DOM结构会随版本更新变化,若选择器失效,需通过浏览器开发者工具重新定位元素。
- CDP命令的支持情况依赖Edge和Selenium的版本兼容性,若出现命令不支持的情况,需升级对应组件。
内容的提问来源于stack exchange,提问作者Adrian Przemysław Drozdowski
相关产品推荐
相关产品推荐

