Alexander
Alexander

Reputation: 971

Selenium in Python switch and focus tab

Open Chrome and new tab:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains

url = 'http://stackoverflow.com/' 

driver = webdriver.Chrome('path_to_chromedriver.exe')
driver.get(url) 
driver.maximize_window()

# open new tab using JavaScript. Focus goes to tab no.2 (new tab)
driver.execute_script("window.open('http://youtube.com/');")

# switch to tab no.1 and go to URL. Focus stays on tab no.2 - how to focus tab no.1?
driver.switch_to.window(driver.window_handles[0])
driver.get('http://google.com/')


Using Selenium in Python 2.7.11 I open two tabs in chrome. I am able to access an individual tab (go to new URL), but I can't focus on the selected tab. For instance, when I open a new tab it goes into focus. When i select the first tab using driver.switch_to.window(driver.window_handles[0]) and try driver.get('http://google.com/') it loads up the new URL, but looking at my screen, I can currently still only see the second tab. In this case I want to be looking at the first tab (Google)

I tried sending user input, but it doesn't work neither for opening a new tab, nor switching between tabs:

actions = ActionChains(driver)    
actions.send_keys(Keys.LEFT_CONTROL + Keys.TAB)
actions.perform()

or

driver.find_element_by_tag_name('body').send_keys(Keys.LEFT_CONTROL + Keys.TAB)

Upvotes: 3

Views: 4292

Answers (1)

Gers
Gers

Reputation: 672

I know it comes a bit late, but it might me useful later
with Selenium 2 (which also supports Python 2.7), this did the trick for me

main_tab = browser.current_window_handle
something_to_open_your_new_tab()
browser.switch_to_window(main_tab)

Upvotes: 1

Related Questions