Handling Browser Windows:
- With the use of Selenium, it is possible to switch between different Tabs(Windows) in a browser and carry out actions on each page.
- Each browser window is assigned a unique address(Window name) that changes dynamically when the browser is opened.
- It is through these addresses only we are able to switch to and perform actions on different tabs.
How do we switch windows/tabs?
By using the "switch_to.window()" function we do switch to different windows/tabs.
Syntax: driver.switch_to.window(window name)
How to get the window names?
In Selenium we have two different methods to get the addresses of windows.
1. current_window_handle
2. window_handles
current_window_handle: By using this function we can get the only address of the parent window(first window).
Syntax: driver.current_window_handle
Example:
- parent_window = driver.current_window_handle
- # print parent window address
- print(parent_window)
- # Switch to the parent window
- driver.switch_to.window(parent_window)
window_handles: By using this function we can get All the windows addresses in a list. To access values in lists use the square brackets[ ] with the index.
Syntax: driver.window_handles
Example:
- windows = driver.window_handles
- # print the All windows addresses
- print(windows)
- # Switch to 1st window
- driver.switch_to.window(window[0])
Example program:
- import time
- from selenium import webdriver
- from selenium.webdriver.common.by import By
- driver = webdriver.Chrome()
- driver.get("https://testingcolleges.blogspot.com/p/windowhandlingdemo1.html")
- newTab = driver.find_element(By.XPATH, "//*[contains(@value, 'New Tab')]")
- newTab.click()
- windows = driver.window_handles
- # print all windows Addresses
- print("All windows IDs: ", windows)
- # switch to 1st window
- driver.switch_to.window(windows[0])
- time.sleep(2)
- #switch to 2nd window
- driver.switch_to.window(windows[1])
- time.sleep(2)
- driver.quite()
OUTPUT:
No comments:
Post a Comment