Python Selenium关闭选项卡
我在我的Python Selenium关闭选项卡,python,python-3.x,selenium,selenium-webdriver,Python,Python 3.x,Selenium,Selenium Webdriver,我在我的Python项目中使用Selenium,有时会打开一个新选项卡(我想使用此选项卡并关闭第一个选项卡),我使用以下代码: window_before = driver.window_handles[0] driver.switch_to_window(window_before) driver.close() time.sleep(2) 之后,我尝试使用以下内容加载新URL: driver.get(mainUrl) 我得到了这个错误: Exception has occurred:
Python
项目中使用Selenium
,有时会打开一个新选项卡(我想使用此选项卡并关闭第一个选项卡),我使用以下代码:
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
知道问题出在哪里吗?您需要返回到未关闭的选项卡,例如:
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)
在下一个请求之前,您需要切换到新窗口,因此请明确使用
driver.switch\u to\u window()