3

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)
1
  • Why not try doing it first in Selenium IDE, then export to Python 2/unittest/WebDriver? Then, look at the resulting code and you may get an idea what you're doing wrong. Note that Selenium IDE is an addon to FireFox, but dealing with tabs is similar in the two browsers.
    – boardrider
    Nov 16, 2016 at 19:20

1 Answer 1

1

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)

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.