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

如何用Python(优选Selenium)检测网站Sources中函数是否执行?

使用Selenium检测指定JS代码行是否执行的方案

核心思路

用Selenium 4自带的DevTools API直接对接浏览器调试协议:给目标JS文件的指定行设置断点,监听断点触发事件,以此判断该行代码是否执行。

具体实现步骤

1. 初始化带调试支持的浏览器实例

先确保装了最新版Selenium和对应浏览器驱动(比如ChromeDriver),然后启动Chrome并拿到调试会话:

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

# 初始化Chrome配置
chrome_options = Options()
# 调试阶段可以不开无头模式,正式运行再加下面这行
# chrome_options.add_argument("--headless=new")

# 启动浏览器
driver = webdriver.Chrome(service=Service("你的chromedriver路径"), options=chrome_options)
# 创建DevTools调试会话
dev_tools_session = driver.create_cdp_session()

2. 找到目标JS文件的脚本ID

要设断点得先拿到目标JS对应的脚本ID,监听脚本加载事件筛选即可:

script_id = None
target_js_file = "目标文件名.js"  # 替换成你要检测的JS文件名

# 监听所有加载的脚本,匹配目标文件
def catch_target_script(event):
    global script_id
    if target_js_file in event["scriptUrl"]:
        script_id = event["scriptId"]
        print(f"找到目标脚本: {event['scriptUrl']},脚本ID: {script_id}")

# 开启调试并绑定监听事件
dev_tools_session.add_listener("Debugger.scriptParsed", catch_target_script)
dev_tools_session.execute_cdp_cmd("Debugger.enable", {})

# 打开目标网页
driver.get("你的目标网站地址")

3. 在指定代码行设置断点

拿到脚本ID后,给目标行加断点(注意DevTools行号从0开始,要减1):

target_line = 463  # 替换成你要检测的代码行

# 设置断点
breakpoint_info = dev_tools_session.execute_cdp_cmd(
    "Debugger.setBreakpoint",
    {
        "location": {
            "scriptId": script_id,
            "lineNumber": target_line - 1  # 行号转成0起始格式
        }
    }
)
breakpoint_id = breakpoint_info["breakpointId"]
print(f"已在第{target_line}行设置断点,断点ID: {breakpoint_id}")

4. 监听断点触发,判断代码是否执行

设个标志位,断点触发就标记代码已执行:

is_executed = False

# 断点触发时的处理逻辑
def on_breakpoint_trigger(event):
    global is_executed
    if event["breakpointId"] == breakpoint_id:
        is_executed = True
        print(f"检测到第{target_line}行代码执行了!")
        # 触发后可以让浏览器继续运行脚本
        dev_tools_session.execute_cdp_cmd("Debugger.resume", {})

# 绑定断点触发监听
dev_tools_session.add_listener("Debugger.breakpointResolved", on_breakpoint_trigger)

# 执行会触发目标代码的操作(比如点击按钮、滚动页面,根据你的场景改)
# driver.find_element(By.ID, "触发按钮ID").click()

# 留足够时间让页面执行脚本
import time
time.sleep(10)

# 输出检测结果
if is_executed:
    print(f"结论:第{target_line}行代码已执行")
else:
    print(f"结论:第{target_line}行代码未执行")

# 清理资源
dev_tools_session.execute_cdp_cmd("Debugger.removeBreakpoint", {"breakpointId": breakpoint_id})
driver.quit()

注意事项

  • 要确保浏览器版本和Selenium的DevTools协议版本兼容,一般最新版Selenium会自动适配,不用手动指定。
  • 如果目标JS是动态加载的,可能需要延长等待时间,确保脚本被捕获到。
  • 部分网站有反调试机制,会禁用Debugger,这种情况需要额外处理(比如绕过反调试脚本)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 05:05:18