Ken Will
Ken Will

Reputation: 53

How do i swap between tabs?

I'm using Selenium (with Firefox) to test a web service and i need to be able to swap between multiple tabs but i don't know how to do that. I tried the following but it doesn't work. What am i doing wrong?

from selenium import webdriver

driver = webdriver.Firefox()

# OPEN UP THE MULTIPLE TABS

for i in driver.window_handles:
    driver.switch_to.window(i) # I HAVE TRIED switch_to_window(i) TOO

I also tried saving each window handle in my own list, and using that instead of window_handles but that didn't work either.

Upvotes: 1

Views: 782

Answers (2)

michael
michael

Reputation: 949

To open multiple windows, you could execute window.open with execute_script :

driver = webdriver.Chrome()

driver.get("https://www.google.co.in/search?q=search1")

driver.execute_script("window.open(arguments[0], 'win2')", \
    "https://www.google.co.in/search?q=search2")

driver.execute_script("window.open(arguments[0], 'win3')", \
    "https://www.google.co.in/search?q=search3")

driver.execute_script("window.open(arguments[0], 'win4')", \
    "https://www.google.co.in/search?q=search4")

driver.switch_to_window("win4")

Upvotes: 1

Piyush
Piyush

Reputation: 521

Here, I give code which open new Tab and Close it.

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

driver = webdriver.Firefox()#Chrome("chromedriver.exe") 
try:
    driver.get("http://www.google.co.in")
    driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 't') 
    driver.get("http://www.stackoverflow.com")
    #driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 'w') 
    driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.TAB) 
    #driver.close()
except Exception as e:
    print e

Upvotes: 2

Related Questions