2

I want do find out what's the handle of the currently active chrome tab with Selenium. I can get all the handles with driver.window_handles and driver.current_window_handle to find out what handle selenium is focused on, but when i now change the tab manually, selenium is still focused on the old tab. How can i now change the focus to the active tab?

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
Schnieker
  • 45
  • 6
  • Why there is a manual intervention ? `but when I now change the tab manually,` – cruisepandey Jan 23 '22 at 16:54
  • My plan was to make an automated chrome for my employees for several websites. So that they can use the selenium chrome normal and when they go to a certain wensite something automated happens. Therefore i need to know what tab is actally active – Schnieker Jan 23 '22 at 17:42

2 Answers2

2

To get the of the currently active tab using Selenium you need to switch_to.window() inducing WebDriverWait for the number_of_windows_to_be() and you can use the following solution:

windows_before  = driver.current_window_handle
print(windows_before)
driver.execute_script("window.open('http://google.com')")
WebDriverWait(driver, 10).until(EC.number_of_windows_to_be(2))
windows_after = driver.window_handles
new_window = [x for x in windows_after if x != windows_before][0]
driver.switch_to.window(new_window)
WebDriverWait(driver, 20).until(EC.title_contains("G"))
print(new_window)

References

You can find a couple of relevant discussions in:

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
1

You can switch to tab 1 using:

driver.switch_to.window(driver.window_handles[1])

Whereas if you want to revert back to tab 0 you can use:

driver.switch_to.window(driver.window_handles[0])

There is also a way to make selenium switch tabs upon pressing CONTROL + TAB

self.driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.TAB)

If you still can’t switch tabs, publish the entire chunk of code and We’ll take a look

Emilio
  • 102
  • 11
  • My plan was to make an automated chrome for my employees for several websites. So that they can use the selenium chrome normal and when they go to a certain wensite something automated happens. Therefore i need to know what tab is actally active – Schnieker Jan 23 '22 at 17:42
  • Maybe [this question](https://stackoverflow.com/questions/35675923/selenium-how-to-get-the-number-of-tabs-opened-in-a-window) can help you identify the tab number on a website – Emilio Jan 23 '22 at 18:29