Testing Automation/01. Selenium
09. Selenium | Switch_to
Jongsung
2022. 3. 19. 15:01
01. Intro
The selenium Webdriver can control the window and iframe using the switch_to method.
02. Testcase
03. switch_to.window()
You can use the window_handle and switch_to.window method.
▶ The first window handle
window_before = self.driver.window_handles[0]
▶ The second window handle
window_after = self.driver.window_handles[1]
Then execute the switch to window method to move to the newly opened window
self.driver.switch_to.window(window_after)
▶ Test code
self.driver.find_element(By.ID, "openwindow").click()
time.sleep(2)
window_before = self.driver.window_handles[0]
window_after = self.driver.window_handles[1]
# Switch to window and search course
self.driver.switch_to.window(window_after)
searchBox = self.driver.find_element(By.NAME, "course")
searchBox.send_keys("python")
time.sleep(2)
self.driver.close()
# Switch back to the parent handle
self.driver.switch_to.window(window_before)
self.driver.find_element(By.ID, 'name').send_keys("test success")
04. switch_to.frame
There are three ways to find iframe.
1. Switch to the frame using ID
self.driver.switch_to.frame("courses-iframe")
2. Switch to the frame using name
self.driver.switch_to.frame("iframe-name")
3. Switch to the frame using number
self.driver.switch_to.frame(0)
How to back to the parent frame
self.driver.switch_to.default_content()
▶ Test code
self.driver.execute_script("window.scrollBy(0,1000);")
# Switch to frame using Id
self.driver.switch_to.frame("courses-iframe")
searchBox = self.driver.find_element(By.NAME, "course")
searchBox.send_keys("python")
time.sleep(2)
# Switch back to the parent frame
self.driver.switch_to.default_content()
self.driver.execute_script("window.scrollBy(0,-1000);")
time.sleep(2)