selenium如何实现,开启浏览器的开发者工具模式

核心配置方案

 
  

pythonCopy Code

# 通用导入方式(适配Selenium 5.x+)
from selenium import webdriver
from selenium.webdriver.common.service import Service

# ---------------------------
# ️ Chrome/Edge 配置方案
# ---------------------------
def chrome_devtools():
    options = webdriver.ChromeOptions()
    options.add_argument("--auto-open-devtools-for-tabs")  # 核心参数
    options.add_argument("--devtools-persistent")          # 持久化模式
    return webdriver.Chrome(service=Service(), options=options)

# ---------------------------
#  Firefox 高级配置
# ---------------------------
def firefox_devtools():
    options = webdriver.FirefoxOptions()
    options.add_argument("--devtools")
    options.set_preference("devtools.toolbox.selectedTool", "inspector")  # 指定默认面板
    return webdriver.Firefox(service=Service(), options=options)

浏览器支持矩阵

浏览器 启动参数 2025兼容性 特色功能
Chrome --auto-open-devtools-for-tabs 网络节流模拟
Edge 同Chrome参数 3D元素分析
Firefox --devtools 多面板自由组合

高级技巧

 
  

pythonCopy Code

# 自定义开发者工具布局(以Chrome为例)
options.add_experimental_option("devToolsPreference", {
    "panelPosition": "bottom",          # 面板位置(right/bottom)
    "showConsoleDrawer": True,          # 显示抽屉式控制台
    "defaultPanel": "performance"       # 启动时默认打开性能面板
})

⚠️ 常见问题排查

 
  

markdownCopy Code

1. ==‌**参数失效警告**‌==  
   → 使用`options.debugger_address = "127.0.0.1:9222"`实现远程调试

2. ==‌**无头模式适配**‌==  
   ```python
   options.add_argument("--headless=new")                   # 新版无头模式
   options.add_argument("--force-device-scale-factor=0.8")  # 缩放适配
  1. 权限问题处理
    添加--disable-dev-shm-usage参数避免内存共享错误
 
  

textCopy Code


━━━━━━━━━━━━━━━━━━━━━━━━━━
==‌**最佳实践建议**‌==:在`conftest.py`中封装配置方法,通过`pytest`命令行参数动态控制开发者工具开关

你可能感兴趣的:(selenium,测试工具)