Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/299.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Selenium关闭选项卡_Python_Python 3.x_Selenium_Selenium Webdriver - Fatal编程技术网

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()