2

I am looking to open up multiple browsers with different sites, and navigate those said browsers. I have written the code to open up the initial browser and navigate freely. However, when I open up the second tab and command it to get a new site, it changes the first browser (initial Safari "tab") to the new site.

Example Shortened code:

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

browser = webdriver.Safari()
browser.get('https://twitter.com')

browser.find_element_by_tag_name('body').
send_keys(Keys.Command+'t')   


browser.get('https://facebook.com')

At this point the "twitter tab (first tab)' changes to facebook, while the second tab, which is the one visibly in front, stays vacant.

How do I get the web-driver to control the second tab?

2 Answers2

1

You can switch between browser tabs/windows as follows:

for handle in browser.window_handles:
    browser.switch_to_window(handle)
Mykola Zotko
  • 15,583
  • 3
  • 71
  • 73
1

try to wait until second tab has handles

browser.find_element_by_tag_name('body').send_keys(Keys.Command+'t')   

WebDriverWait(browser, 5).until(
    lambda b: len(b.window_handles) != 1
)
# switch to second tab
browser.switch_to_window(browser.window_handles[1]) # or [-1] for latest tab
browser.get('https://facebook.com')
ewwink
  • 18,382
  • 2
  • 44
  • 54
  • browser.switch_to_window(browser.window_handles[1]) # or [-1] for latest tab. # A variation of this line seemed to do the trick. – Joseph Trocchio Jan 03 '19 at 13:23