Your ultimate guide

Handling Browser Windows using Python with Selenium


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:
  1. parent_window = driver.current_window_handle
  2. # print parent window address
  3. print(parent_window)
  4. # Switch to the parent window
  5. 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:
  1. windows = driver.window_handles
  2. # print the All windows addresses
  3. print(windows)
  4. # Switch to 1st window
  5. driver.switch_to.window(window[0]) 


Example program:
  1. import time
  2. from selenium import webdriver
  3. from selenium.webdriver.common.by import By

  4. driver = webdriver.Chrome()
  5. driver.get("https://testingcolleges.blogspot.com/p/windowhandlingdemo1.html")
  6. newTab = driver.find_element(By.XPATH, "//*[contains(@value, 'New Tab')]")
  7. newTab.click() 
  8. windows = driver.window_handles
  9. # print all windows Addresses
  10. print("All windows IDs: ", windows)
  11. # switch to 1st window
  12. driver.switch_to.window(windows[0])
  13. time.sleep(2)
  14. #switch to 2nd window
  15. driver.switch_to.window(windows[1])
  16. time.sleep(2)
  17. driver.quite()
OUTPUT:
    





No comments:

Post a Comment