You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Selenium执行中如何自动打开开发者工具(非PyAutoGUI方式)

在指定时机用Selenium打开开发者工具(无需PyAutoGUI)

方法1:使用Chrome DevTools Protocol(CDP)

这是最可靠的方案,无需模拟按键,直接通过浏览器调试协议命令触发开发者工具,完全可控触发时机。

示例代码(Python):

from selenium import webdriver
from selenium.webdriver.chrome.service import Service

# 初始化Chrome驱动
driver = webdriver.Chrome(service=Service("你的chromedriver路径"))

# 导航到目标页面
driver.get("https://example.com")

# 执行业务操作...

# 在指定时机调用CDP命令打开开发者工具
driver.execute_cdp_cmd("Emulation.setShowDebuggerUI", {"show": True})

# 若需要关闭,可执行:
# driver.execute_cdp_cmd("Emulation.setShowDebuggerUI", {"show": False})

注意:Chrome、Edge等基于Chromium的浏览器通用上述命令,无需考虑系统差异。

方法2:修正ActionChains按键模拟逻辑

如果坚持用按键模拟,之前失败大概率是因为浏览器窗口未获得焦点,或按键组合写法错误。试试以下修正后的代码:

示例代码(Python):

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.service import Service

driver = webdriver.Chrome(service=Service("你的chromedriver路径"))
driver.get("https://example.com")

# 执行业务操作...

# 强制切换到当前窗口,确保浏览器获得焦点
driver.switch_to.window(driver.current_window_handle)

# Windows/Linux环境:模拟Ctrl+Shift+I
actions = ActionChains(driver)
actions.key_down(Keys.CONTROL).key_down(Keys.SHIFT).send_keys('i').key_up(Keys.SHIFT).key_up(Keys.CONTROL).perform()

# Mac环境替换为:
# actions.key_down(Keys.COMMAND).key_down(Keys.OPTION).send_keys('i').key_up(Keys.OPTION).key_up(Keys.COMMAND).perform()

# 也可以直接模拟F12按键
# actions.send_keys(Keys.F12).perform()

之前方法失效的常见原因

  • 直接给body元素发按键:body元素未获取焦点,按键事件被浏览器忽略
  • ActionChains未生效:未调用perform()方法,或浏览器窗口未激活导致焦点不在浏览器内
  • 启动时自动打开开发者工具:仅能在浏览器启动时触发,无法在运行时指定时机执行

内容的提问来源于stack exchange,提问作者John Doe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 03:55:16