'How can I open a new window and close the previous one? with python and selenium

I have a list of links (url), I need that each link opens in a different tab, example:

  • youtube.com
  • google.com
  • facebook.com

The script will open youtube, then in another window, it will open google, but I need to close the youtube tab, then I need to open the facebook tab.

My code is:

    if(posts!=len(data)-1):
           driver.execute_script("window.open('');")
           chwd = driver.window_handles
           driver.switch_to.window(chwd[-1])
           driver.close()
           driver.switch_to.window(chwd[-2])
    driver.quit()


Solution 1:[1]

I assume you have the only one opened window before driver.execute_script("window.open('');").

Try

if(posts!=len(data)-1):
           old_window = driver.window_handles[0]
           driver.execute_script("window.open('');")
           driver.switch_to.window(old_window)
           driver.close()
           driver.switch_to.default_content()
    driver.quit()

Solution 2:[2]

wait=WebDriverWait(driver,60)   
urls=["https://www.youtube.com/","https://www.google.com/"]
chwd = driver.window_handles
for url in urls:
    old = driver.current_window_handle 
    driver.execute_script("window.open('{arguments[0]');",url)
    wait.until(EC.number_of_windows_to_be(len(chwd)+1))
    driver.switch_to.window(old)
    driver.close()
    driver.switch_to.default_content()
driver.quit()

I would do it like this to close the window as soon it opens so you can don't accidentally close stuff. Then switch back to default.

Imports:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait 
from selenium.webdriver.support import expected_conditions as EC

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Max Daroshchanka
Solution 2 marc_s