How do I count number of tabs are being opened in Browser by using Python Selenium?
2 Answers
How do I count number of tabs are being opened in Browser by using Python Selenium?
Since provided link answer doesn't have any answer in python, you can get the count number of tabs opened in browser using WebDriver#window_handles as below :-
len(driver.window_handles)
Comments
For getting the Number of Opened tabs You can use the code below-
The below code will return length as "1" if single tab is opened or "2" if two tabs are opened.
len(driver.window_handles)
Further If you want to Close all the extra opened tabs and want to keep only the 1st tab opened then try the below Code-
driver_len = len(driver.window_handles) #fetching the Number of Opened tabs
print("Length of Driver = ", driver_len)
if driver_len > 1: # Will execute if more than 1 tabs found.
for i in range(driver_len - 1, 0, -1):
driver.switch_to.window(driver.window_handles[i]) #will close the last tab first.
driver.close()
print("Closed Tab No. ", i)
driver.switch_to.window(driver.window_handles[0]) # Switching the driver focus to First tab.
else:
print("Found only Single tab.")