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

如何用Python+Selenium判断Chrome已开多页面是否含指定URL

检测Chrome多标签页中是否存在指定URL

你的代码只能获取当前激活的标签页信息,要遍历所有打开的标签页,需要操作窗口句柄,以下是解决方法:

前提条件

确保Chrome是通过远程调试模式启动的,启动命令示例:

chrome.exe --remote-debugging-port=8888

(Mac/Linux环境下,将chrome.exe替换为google-chrome)

完整代码

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

# 连接到已打开的Chrome调试会话
options = Options()
options.add_experimental_option("debuggerAddress", "127.0.0.1:8888")
browser = webdriver.Chrome(options=options)

# 替换为你要检测的目标URL
target_url = "https://your-target-url.com"

# 遍历所有标签页句柄
for handle in browser.window_handles:
    # 切换到当前标签页
    browser.switch_to.window(handle)
    current_url = browser.current_url
    
    # 检查URL是否匹配(这里用包含匹配,可根据需求改为精确匹配)
    if target_url in current_url:
        print(f"找到目标URL:{current_url}")
        # 可选:激活该标签页
        # browser.switch_to.window(handle)
        break
else:
    print("未找到包含目标URL的标签页")

# 不要调用quit(),避免关闭原有Chrome窗口

关键说明

  • browser.window_handles:返回所有打开标签页的句柄列表
  • switch_to.window(handle):切换到指定句柄对应的标签页
  • current_url:获取当前标签页的完整URL,可根据需求选择==(精确匹配)或in(包含匹配)
  • 避免调用browser.quit(),否则会关闭整个Chrome进程,影响你原本打开的页面

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 17:07:00