Home > database >  How to get the handle of the currently active tab with Selenium and Python
How to get the handle of the currently active tab with Selenium and Python

Time:01-24

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?

CodePudding user response:

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

CodePudding user response:

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:

  •  Tags:  
  • Related