首页 > 解决方案 > Python Selenium 关闭选项卡

问题描述

Selenium在我的Python项目中使用,有时会打开一个新选项卡(我想使用此选项卡并关闭第一个选项卡),我使用以下代码进行操作:

window_before = driver.window_handles[0]
driver.switch_to_window(window_before)
driver.close()

time.sleep(2)

之后,我尝试加载一个新的 URL:

driver.get(mainUrl)

我得到这个错误:

Exception has occurred: NoSuchWindowException
Message: no such window: target window already closed
from unknown error: web view not found

知道有什么问题吗?

标签: pythonpython-3.xseleniumselenium-webdriver

解决方案


您需要返回未关闭的 TAB,例如:

window_to_close = driver.window_handles[0]
window_to_keep = driver.window_handles[1]
driver.switch_to_window(window_to_close)
driver.close()
driver.switch_to_window(window_to_keep)

driver.get(mainUrl)

推荐阅读