11

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

1

2 Answers 2

17

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)
Sign up to request clarification or add additional context in comments.

Comments

4

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.")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.