【问题标题】:Selenium get session ID of new window - PythonSelenium 获取新窗口的会话 ID - Python
【发布时间】:2017-10-21 06:37:39
【问题描述】:

我正在使用 Selenium 对 Chrome 进行一些检查。 我会自动浏览到“chrome://flags/#enable-quic”,然后在下拉菜单中(自动)选择“启用”。 如下所述,必须重新启动才能使更改生效。 我想在重新启动的新窗口上打开一个新选项卡来做更多的事情。

代码片段:

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

我得到的例外是:

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

有人知道如何处理这个问题吗?

谢谢

【问题讨论】:

    标签: python selenium selenium-webdriver automated-tests


    【解决方案1】:

    单击"Refresh" 按钮后,您将获得新的Chrome 窗口。你应该在执行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');")
    

    【讨论】:

      【解决方案2】:

      重新启动 Chrome 是个坏主意,因为 Chromedriver 引用了原始 chrome 进程。

      no such window: window was already closed

      所以...browser 仍然指向旧窗口。

      不要尝试重新启动 Chrome,只需在创建 Chromedriver 实例时设置选项即可。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-23
        • 1970-01-01
        • 2013-03-23
        • 2015-02-23
        • 1970-01-01
        • 1970-01-01
        • 2023-04-01
        • 1970-01-01
        相关资源
        最近更新 更多