How do I count number of tabs are being opened in Browser by using Python Selenium?
The below code will return length as "1" if single tab is opened or "2" if two tabs are opened. 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.
Ways to open multiple tabs using Selenium: We need to call “execute_script” method which in turn executes window. open('about:blank', 'secondtab') javascript. Then we need to switch to that tab and for that tab can give any valid URL.
The total number of links in a page can be counted with the help of findElements() method. The logic is to return a list of web elements with tagname anchor, then getting the size of that list.
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)
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.")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With