Open new tab and close the previous tab python selenium

Viewed 45

I want to open a new tab and close the previous tab. But it seems doesn't work! it just open the first link and throws the error: no such window: target window already closed

from selenium import webdriver
driver = webdriver.Chrome()

urls = ['https://google.com','https://facebook.com','https://instagram.com']

for i in range(3):
    driver.execute_script("window.open('"+ str(urls[i]) +"');")
    driver.close()

Thanks in advance!

1 Answers

After opening a new tab you need to close the current (old) tab and then to switch to the new tab.
The code below works

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options

options = Options()
options.add_argument("start-maximized")
webdriver_service = Service('C:\webdrivers\chromedriver.exe')
driver = webdriver.Chrome(service=webdriver_service, options=options)
urls = ['https://google.com', 'https://facebook.com', 'https://instagram.com']

for i in range(3):
    # open a new tab
    driver.execute_script("window.open('" + str(urls[i]) + "');")
    # close the current, old tab
    driver.close()
    # get the handle of the new, recently opened tab
    window_name = driver.window_handles[0]
    # switch to the recently opened tab
    driver.switch_to.window(window_name=window_name)
Related