11

I am using Python. I am trying to open two tabs on chrome, each to a different website. This is my code:

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


browser=webdriver.Chrome()
browser.get('http:/reddit.com')
browser.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 't')
time.sleep(3)
browser.get('http://bing.com')

When I run it, the first tab is opened to reddit.com, and then another tab opens to my default webpage, and then bing.com is opened in the original tab. I want the first tab to go to Reddit and the second tab to go to bing, but browser.get('website') only acts on the first tab.

Ratmir Asanov
  • 6,237
  • 5
  • 26
  • 40
Shock-o-lot
  • 135
  • 1
  • 1
  • 11

3 Answers3

46

To interact with a window, you need to set the context to that window with driver.switch_to.window. It would also be easier to open a new tab with a script injection:

browser=webdriver.Chrome()

#first tab
browser.get('http:/reddit.com')

#second tab
browser.execute_script("window.open('about:blank', 'tab2');")
browser.switch_to.window("tab2")
browser.get('http://bing.com')
Florent B.
  • 41,537
  • 7
  • 86
  • 101
  • I am not familiar with script injection. What does execute_script("window.open('about:blank', 'tab2');") mean? – Shock-o-lot Sep 01 '16 at 22:54
  • 1
    It will execute the JavaScript string provided as argument. In this case, it will open a new tab named `tab2`. For further information: https://developer.mozilla.org/en-US/docs/Web/API/Window/open – Florent B. Sep 01 '16 at 22:58
14

try like this for python:

browser=webdriver.Chrome()
browser.get('http:/reddit.com')
window_before = driver.window_handles[0]
browser.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 't')
window_after = driver.window_handles[1]
driver.switch_to_window(window_after)
time.sleep(3)
browser.get('http://bing.com')
Jason
  • 156
  • 1
  • 5
  • The order in which the handles are returned is arbitrary. Thus, you shouldn't use the second index to return the second window. https://www.w3.org/TR/webdriver/#dfn-get-window-handles – Florent B. Sep 01 '16 at 23:17
-1

You should switch to other tab to interact with it.

ArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles());
driver.switchTo().window(tabs.get(0));//first tab
driver.switchTo().window(tabs.get(1));//second tab
Taylan Derinbay
  • 128
  • 3
  • 13