Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count number of tabs open in Selenium Python

How do I count number of tabs are being opened in Browser by using Python Selenium?

like image 748
Fajri Koto Avatar asked Oct 12 '16 18:10

Fajri Koto


People also ask

How do I count tabs in 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.

How does Python handle multiple tabs in selenium?

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.

How do you count the number of elements in a list in selenium?

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.


Video Answer


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)
like image 145
Saurabh Gaur Avatar answered Sep 27 '22 17:09

Saurabh Gaur


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.")
like image 25
Amar Kumar Avatar answered Sep 27 '22 17:09

Amar Kumar