Python和Selenium-关闭所有选项卡而不关闭浏览器 [英] Python and Selenium - Close all tabs without closing the browser

查看:655
本文介绍了Python和Selenium-关闭所有选项卡而不关闭浏览器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想关闭所有打开的选项卡(浏览器窗口),而无需实际关闭驱动程序,因为我想继续使用它.

I want to close all open tabs (browser windows) without actually closing the driver, because I want to keep using it.

driver.close()只会关闭焦点标签.
driver.quit()将关闭它们,但也退出驱动程序.

driver.close() will just close the focused tab.
driver.quit() will close them all but also quit the driver.

我考虑过使用 driver.quit() ,然后重新打开驱动程序.但这似乎不是很干净.也许这是超级干净,但也很慢.

I thought about using driver.quit() and then re-opening the driver. But it does not seem very clean. Or maybe it is super clean, but also a slow thing to do.

注意:通过 geckodriver

我该如何处理?

推荐答案

您可以通过向页面发送ctrl + w来关闭选项卡,直到没有剩余的选项卡为止.记录一下您打开了多少个标签,并使用循环将其关闭

You can close the tabs by sending ctrl + w to the page until you don't have any tabs left. Keep a record of how many tabs you opened and use a loop to close them

from selenium.webdriver.common.keys import Keys

num_of_tabs = ...
for x in range(1, num_of_tabs):
    self.driver.find_element_by_tag_name('body').send_keys(Keys.COMMAND + 'W')

这将关闭除一个选项卡以外的所有选项卡.关闭最后一个不会关闭driver,但是您将无法使用它.

This will close all the tabs but one. Closing the last one will not close the driver, but you won't be able to use it.

这篇关于Python和Selenium-关闭所有选项卡而不关闭浏览器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆