user15048082
user15048082

Reputation:

Closing Popup windows in Selenium using python

I am trying to close popup windows, and the handler values are not fixed, they change every time when run again. I thought of pulling the pop title and using for loop to close() the popups but the popup didn't have a title.

driver = webdriver.Chrome()
wait = WebDriverWait(driver, 10)
driver.get('https://www.naukri.com/')
# driver.maximize_window()

parent = driver.current_window_handle
print(f"This is parent window : {parent}")

uselessWindows = driver.window_handles
print(f"This has the parent window and also the two popup windows : {uselessWindows}")

and the output is

This is parent window : CDwindow-196D8EFD5DD167AUTHE8935233FE0140 #String Value
This has the parent window and also the two popup window : ['CDwindow-196D8EFD5DD167AUTHE8935233FE0140', 'CDwindow-9E2058C9AADEWDHUIO4758B2F378AF577', 'CDwindow-94B59B8JGUTJ46578DHKDLNM24658C7C'] #List Value

Every time the value after "CDwindow -" changes every single time and I am unable to use set difference - because the current_window_handle is in the string and the window_handles is in List. Kindly help me with a solution to close the popups.

Upvotes: 2

Views: 9264

Answers (2)

PDHide
PDHide

Reputation: 19929

parent = driver.current_window_handle
print(f"This is parent window : {parent}")

uselessWindows = driver.window_handles
print(
    f"This has the parent window and also the two popup windows : {uselessWindows}")
driver.switch_to.window(uselessWindows[-1])
driver.close()
driver.switch_to.window(uselessWindows[0])

the pop up window is the last element in the list you can use above code , you have to switch back to parent to continue execution

Upvotes: -1

Buaban
Buaban

Reputation: 5137

You have to iterate through the list of window handles, and close the one which is not the parent.

driver.get('https://www.naukri.com/')
parent = driver.current_window_handle
uselessWindows = driver.window_handles
for winId in uselessWindows:
    if winId != parent: 
        driver.switch_to.window(winId)
        driver.close()

Upvotes: 3

Related Questions