Search code examples
pythonseleniumwebbotsdriver

Get index of user visiting tab selenium python


I am trying to get the index or window id of currently visiting page not the active tab.

I am trying to access a specific tab in multiple tabs opened by bot I want to know that if user clicked on the unfocused tab e.g. tab no 3 but the active/focus tab is tab no 6. I want to shift the focus to user visiting page.

Sample code of mine which is not working.

for i in web.window_handles:
    if not web.execute_script("return document.visibilityState") == "visible":
        web.switch_to.window(i)
        current_opened_window = web.current_window_handle

    else:
        current_opened_window = i

Sample Picture


Solution

  • Presumably Selenium can focus only on a specific tab at a time and to shift the focus to other tabs you need tab handling.

    Hence, any click attempt on a WebElement will try to locate the element on the focused tab/page first. Incase the element isn't found NoSuchElementException would be raised.