Search code examples
pythonseleniumselenium-webdriverbrowserwindow

Python - How can i open multiple browser windows


I am new to python and I will be using the code below to open a browser window and do some things. However, when I open multiple URLs simultaneously, it just opens a new tab in the existing browser window, but I want it to open in a new window and then open more tabs on the new window(s). Here is the code

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
import webbrowser

#path for the driver
driver  = webdriver.Chrome(executable_path="C:\mydriver\chromedriver")

driver.get("https://www.google.com")
driver.execute_script("window.open ('https://www.google.com', 'new window')")
driver.switch_to.window(driver.window_handles[0])

driver.execute_script("window.open ('https://www.bing.com','https://www.facebook.com', 'new window')")
driver.switch_to.window(driver.window_handles[1])

Solution

  • Try this:

    from selenium import webdriver
    from selenium.webdriver.common.keys import Keys
    from selenium.webdriver.common.action_chains import ActionChains
    import webbrowser
    
    #path for the driver
    driver  = webdriver.Chrome(executable_path="C:\mydriver\chromedriver")
    
    driver.get("https://www.google.com")
    driver.execute_script("window.open ('https://www.google.com', 'new window')")
    driver.switch_to.window(driver.window_handles[0])
    
    for page in ('https://www.bing.com','https://www.facebook.com'):
        driver.execute_script(f"window.open ('{page}')")
    driver.switch_to.window(driver.window_handles[1])