Selenium:通过索引关闭特定选项卡(句柄)而无需切换到它

发布于 2025-02-07 22:14:30 字数 252 浏览 4 评论 0 原文

是否可以在

目前,我正在这样做:

driver.switch_to.window(driver.window_handles[1])
driver.close()
driver.switch_to.window(driver.window_handles[0])

我发现切换选项卡会使我的脚本非常不稳定,因此我希望在可能的情况下避免使用。

Is it possible to close a specific tab in Selenium by index wihout switching to it?

Currently I am doing this:

driver.switch_to.window(driver.window_handles[1])
driver.close()
driver.switch_to.window(driver.window_handles[0])

I found that switching tabs makes my script very unstable, so I would prefer to avoid it if possible.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

悲凉≈ 2025-02-14 22:14:30

WebDriver可以关闭窗口/TAB 实例,如果它专注于该特定 TAB Windows

因此,如果您专注于不同的选项卡 Windows ,则无法关闭选项卡或Windows

如果您面对不稳定脚本执行时,请执行 tabs/windows 我会说有 time.sleep(2) time。睡眠(3)应该可以帮助您解决或摆脱不稳定。

还请记住,驱动程序将关闭所有实例。

WebDriver can close a window/tab instance if it has the focus on that particular tab or windows.

So you can not close a tab or windows if you are focusing on a different tab or windows.

If you are facing unstable script execution while switching tabs/windows I'd say have time.sleep(2) or time.sleep(3) that should help you resolve or get rid off un-stable.

Also remember, driver.quit would close all the instances.

漫雪独思 2025-02-14 22:14:30

实际上,如果使用 chromedriver ,但它需要使用 Chrome开发人员工具协议(在硒4中支持)。

更具体地说:您必须:

  1. 使用 getTarget.getTargets 方法。
  2. 提取要关闭的页面(目标)的 targetID
  3. 使用 targetId 。

Actually it is possible if using chromedriver but it requires to use Chrome Developer Tools Protocol (which is supported in Selenium 4).

More specifically you have to:

  1. Get list of targets using Target.getTargets method.
  2. Extract the targetId of the page (target) you want to close.
  3. Close the page (target) using Target.closeTarget method passing the targetId.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文