Windows处理如果我试图关闭python中的当前窗口,则关闭整个浏览器



我目前正在使用窗口处理来打开新窗口中的映射方向,在它打开后,我将关闭打开的子窗口,并在代码中进行重新命名工作。但它关闭了整个浏览器,同时调试它正常工作,但在运行代码时,我得到的错误是,

错误-selenium.common.exceptions.NoSuchWindowException: Message: no such window: target window already closed

我已经附上了代码,

##Clicking on The Map Image
self.driver.find_element_by_xpath("/html[1]/body[1]/div[1]/div[2]/div[1]/section[1]/div[1]/div[1]/div[2]/div[1]/a[1]/img[1]").click()
##Setting up an Window Handle to get the size.
handels =self.driver.window_handles
size = len(handels)
"""
The Below For Loop, We are using For Handling The Mutilple Windows,
Which are opened in the Browser.
"""
for length in range(size):
driver.switch_to.window(handels[length])
print(self.driver.title)
time.sleep(3)
if length == 1:
driver.close()

我不知道我在哪里犯了错。请帮我整理一下。

尝试此代码关闭新窗口并切换回主窗口

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# Get current window
current = self.driver.current_window_handle
# Get current windows
handles = self.driver.window_handles
# Click button. Consider to use more reliable relative XPath instead of this absolute XPath
self.driver.find_element_by_xpath("/html[1]/body[1]/div[1]/div[2]/div[1]/section[1]/div[1]/div[1]/div[2]/div[1]/a[1]/img[1]").click()
# Wait for new window
WebDriverWait(self.driver, 10).until(EC.new_window_is_opened(handles))
# Switch to new window
self.driver.switch_to.window([w for w in self.driver.window_handles if w != current][0])
# Close new window
self.driver.close()
# Switch back to main window
self.driver.switch_to.window(current)

简而言之,切换到新窗口句柄并不干净。

解决方案

  • 始终跟踪父窗口句柄,以便稍后根据您的用例进行遍历
  • 选项卡/Windows之间切换之前,请始终将WebDriverWait与预期的条件一起用作number_of_windows_to_be(num_windows)
  • 始终跟踪子窗口句柄,以便在需要时进行遍历
  • 提取页面标题之前,请始终将WebDriverWaitexpected_conditions一起用作title_contains("partial_page_title")
  • 这是你自己的代码,上面提到了一些小的调整:

    from selenium import webdriver
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    handels_initially  = driver.window_handles
    self.driver.find_element_by_xpath("/html[1]/body[1]/div[1]/div[2]/div[1]/section[1]/div[1]/div[1]/div[2]/div[1]/a[1]/img[1]").click()
    WebDriverWait(driver, 10).until(EC.number_of_windows_to_be(2))
    handels_now =self.driver.window_handles
    new_handle = [x for x in handels_now if x != handels_initially][0]
    driver.switch_to.window(new_handle)
    WebDriverWait(driver, 20).until(EC.title_contains("partial_title"))
    print(self.driver.title)
    driver.close()
    
  • 您可以在Selenium Switch Tabs 中找到详细的讨论

最新更新