Reputation: 330
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!
Upvotes: 0
Views: 2830
Reputation: 134
if you are using Selenium 4 and later versions. Please try this code
driver.switch_to.new_window('tab')
driver.implicitly_wait(20)
driver.get(linkURL)
it will open url in new tab
Upvotes: 1
Reputation: 33361
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)
Upvotes: 1