niceGuy
niceGuy

Reputation: 321

Selenium get session ID of new window - Python

I am using Selenium in order to perform some checks on Chrome. I'm automatically browsing to "chrome://flags/#enable-quic" and there in the drop down I (automatically) choose "Enable". As written below, one has to relaunch in order for the changes to take effect. I want to open a new tab on the new re-launched window to do some more stuff.

A snip of the code:

browser = webdriver.Chrome()
browser.get("chrome://flags/#enable-quic")
browser.find_element_by_xpath("//*[@id='enable-quic']/table/tbody/tr/td/div[1]/div/div[2]/select/option[2]").click() #Select "Enable"
time.sleep(5)
browser.find_element_by_xpath("//*[@id='flagsTemplate']/div[5]/button").click() #Click relaunch
time.sleep(5)
browser.execute_script("window.open('https://www.gmail.com');")  #Exception after this line

The exception I get is:

selenium.common.exceptions.NoSuchWindowException: Message: no such window: window was already closed

Someone has an idea how to handle this?

Thanks

Upvotes: 2

Views: 2072

Answers (2)

Corey Goldberg
Corey Goldberg

Reputation: 60604

re-launching Chrome is a bad idea because Chromedriver has a reference to the original chrome process.

no such window: window was already closed

so... browser is still pointing to the old window.

Instead of trying to relaunch Chrome, just set the option when you create a Chromedriver instance.

from selenium import webdriver

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--enable-quic')
chrome = webdriver.Chrome(chrome_options=chrome_options)

Upvotes: 2

Andersson
Andersson

Reputation: 52665

After clicking "Refresh" button you get new Chrome window. You should try to switch to that window before executing JavaScript:

browser = webdriver.Chrome()
browser.get("chrome://flags/#enable-quic")
browser.find_element_by_xpath("//div[@id='enable-quic']//select[@class='experiment-select']/option[2]").click()
time.sleep(5)
browser.find_element_by_xpath("//button[@class='experiment-restart-button']").click()
time.sleep(5)
browser.switch_to.window(browser.window_handles[0])
browser.execute_script("window.open('https://www.gmail.com');")

Upvotes: 2

Related Questions