- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to switch different browser tabs using Python Selenium?
We can switch different browser tabs using Selenium webdriver in Python using the method switch_to.window. By default, the webdriver has access to the parent window.
Once another browser tab is opened, the switch_to.window helps to switch the webdriver focus to the tab. The window handle of the browser window where we want to shift is passed as a parameter to that method.
The method window_handles contains the list of all window handle ids of the opened browsers. The method current_window_handle is used to hold the window handle id of the browser window in focus.
Syntax
p = driver.current_window_handle parent = driver.window_handles[0] chld = driver.window_handles[1] driver.switch_to.window(chld)
Let us make an attempt to access the below browser tabs −
Example
from selenium import webdriver #set chromodriver.exe path driver = webdriver.Chrome(executable_path="C:\chromedriver.exe") driver.implicitly_wait(0.5) #launch URL driver.get("https://the-internet.herokuapp.com/windows") #identify element l = driver.find_element_by_link_text("Click Here") l.click() #obtain window handle of browser in focus p = driver.current_window_handle #obtain parent window handle parent = driver.window_handles[0] #obtain browser tab window chld = driver.window_handles[1] #switch to browser tab driver.switch_to.window(chld) print("Page title for browser tab:") print(driver.title) #close browser tab window driver.close() #switch to parent window driver.switch_to.window(parent) print("Page title for parent window:") print(driver.title) #close browser parent window driver.close()
Output
Advertisements