Windows Handling Closes The Whole Browser If I Try To Close The Current Window In Python
Am currently using windows handling for opening the map direction in the new window and after it opens i will be closing the child window, which is opened and do the remaming work
Solution 1:
Try this code to close new window and switch back to main window
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)
Solution 2:
In short the switching to the new window handle wasn't clean.
Solution
- Always keep track of the Parent Window handle so you can traverse back later if required as per your usecase.
- Always use WebDriverWait with expected_conditions as
number_of_windows_to_be(num_windows)
before switching between Tabs/Windows. - Always keep track of the Child Window handles so you can traverse whenever required.
- Always use WebDriverWait with
expected_conditions
astitle_contains("partial_page_title")
before extracting the Page Title. Here is your own code with some minor tweaks mentioned above:
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()
You can find a detailed discussion in Selenium Switch Tabs
Post a Comment for "Windows Handling Closes The Whole Browser If I Try To Close The Current Window In Python"