[파이썬] Selenium 다중 윈도우 핸들링

Handling multiple windows in Selenium can be a common requirement while automating web applications. In this blog post, we will explore how to handle multiple windows using Selenium in Python.

Scenario

Imagine a scenario where you have clicked on a link/button on a web page and it opens a new window. You need to automate actions in both the windows, such as interacting with elements or extracting information.

Solution

Selenium provides a way to handle multiple windows by using the window_handles property. This property returns a list of all the window handles currently opened by the browser. Each window handle can be treated as a separate window instance, allowing us to switch between windows and perform operations accordingly.

Here is an example code snippet for handling multiple windows in Selenium Python:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# Create a new instance of the Firefox driver
driver = webdriver.Firefox()

# Navigate to the initial web page
driver.get("https://example.com")

# Perform an action that opens a new window
new_window_button = driver.find_element(By.XPATH, "//button[@id='new-window']")
new_window_button.click()

# Switch to the new window
driver.switch_to.window(driver.window_handles[1])

# Wait for an element to be present in the new window
wait = WebDriverWait(driver, 10)
element = wait.until(EC.presence_of_element_located((By.XPATH, "//input[@id='username']")))

# Perform actions in the new window
element.send_keys("username")
submit_button = driver.find_element(By.XPATH, "//button[@id='submit']")
submit_button.click()

# Switch back to the original window
driver.switch_to.window(driver.window_handles[0])

# Perform actions in the original window
# ...

# Close the browser
driver.quit()

In the above example, we first open the initial webpage using the Firefox driver. Then, we locate and click on a button/link that opens a new window. We switch to the new window using the switch_to.window() method and carry out operations specific to that window.

After completing the actions in the new window, we switch back to the original window using the same method and continue with further operations if needed.

Conclusion

Handling multiple windows in Selenium Python is straightforward with the provided window_handles property. By switching between windows using the switch_to.window() method, we can perform actions and automate the flow across multiple windows in a web application.

Remember to handle exceptions and add waiting mechanisms to ensure smooth execution, especially when dealing with multiple windows.