GVKun编程网logo

通过Python3使用Selenium和WebDriver切换选项卡时,“ NoSuchWindowException:没有这样的窗口:窗口已经关闭”

31

在本文中,我们将详细介绍通过Python3使用Selenium和WebDriver切换选项卡时,“NoSuchWindowException:没有这样的窗口:窗口已经关闭”的各个方面,同时,我们也将为

在本文中,我们将详细介绍通过Python3使用Selenium和WebDriver切换选项卡时,“ NoSuchWindowException:没有这样的窗口:窗口已经关闭”的各个方面,同时,我们也将为您带来关于c# – .NET Selenium NoSuchElementException; WebDriverWait.Until()不起作用、OpenQA.Selenium.NoSuchElementException:没有这样的元素:无法定位元素 C# 按类查找、org.openqa.selenium.InvalidCookieDomainException:使用Selenium和WebDriver禁止文档访问Cookie、org.openqa.selenium.NoSuchWindowException的实例源码的有用知识。

本文目录一览:

通过Python3使用Selenium和WebDriver切换选项卡时,“ NoSuchWindowException:没有这样的窗口:窗口已经关闭”

通过Python3使用Selenium和WebDriver切换选项卡时,“ NoSuchWindowException:没有这样的窗口:窗口已经关闭”

我有一个表单,当我单击它时会在新选项卡中打开。当我尝试导航到该新选项卡时,我不断收到NoSuchWindowException。代码非常简单。“
myframe”是新标签中最终将被插入信息的框架。我应该再等吗?

from selenium import webdriverfrom selenium.webdriver.support import expected_conditions as ECfrom selenium.webdriver.support.ui import WebDriverWait, Selectfrom selenium.webdriver.common.by import Byfrom selenium.common.exceptions import TimeoutException, NoSuchElementExceptionimport timeimport pandas as pdurl = *****driver = webdriver.Chrome(executable_path = r''S:\Engineering\Jake\MasterControl Completing Pipette CalPM Forms\chromedriver'')driver.get(url)wait = WebDriverWait(driver, 5)window_before = driver.window_handles[0]driver.find_element_by_id(''portal.scheduling.prepopulate'').click()window_after = driver.window_handles[1]driver.switch_to_window(window_after)driver.switch_to_default_content()wait.until(EC.frame_to_be_available_and_switch_to_it(''myframe''))

Traceback (most recent call last):  File "<ipython-input-308-2aa72eeedd51>", line 1, in <module>    runfile(''S:/Engineering/Jake/MasterControl Completing Pipette CalPM Forms/Pipette Completing CalPM Tasks.py'', wdir=''S:/Engineering/Jake/MasterControl Completing Pipette CalPM Forms'')  File "C:\ProgramData\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 678, in runfile    execfile(filename, namespace)  File "C:\ProgramData\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 106, in execfile    exec(compile(f.read(), filename, ''exec''), namespace)  File "S:/Engineering/Jake/MasterControl Completing Pipette CalPM Forms/Pipette Completing CalPM Tasks.py", line 150, in <module>    create_new_cal_task(asset_number)  File "S:/Engineering/Jake/MasterControl Completing Pipette CalPM Forms/Pipette Completing CalPM Tasks.py", line 130, in create_new_cal_task    driver.switch_to_default_content()  File "C:\ProgramData\Anaconda3\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 783, in switch_to_default_content    self._switch_to.default_content()  File "C:\ProgramData\Anaconda3\lib\site-packages\selenium\webdriver\remote\switch_to.py", line 65, in default_content    self._driver.execute(Command.SWITCH_TO_FRAME, {''id'': None})  File "C:\ProgramData\Anaconda3\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 314, in execute    self.error_handler.check_response(response)  File "C:\ProgramData\Anaconda3\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response    raise exception_class(message, screen, stacktrace)NoSuchWindowException: no such window: window was already closed  (Session info: chrome=68.0.3440.106)  (Driver info: chromedriver=2.40.565498 (ea082db3280dd6843ebfb08a625e3eb905c4f5ab),platform=Windows NT 6.1.7601 SP1 x86_64)

答案1

小编典典

感谢Debanjan(并为以后的回复表示歉意-刚回到办公室)。我能够通过使用解决此问题

While True:    try:        [navigate to the new frame, wait for a specific element to show up]        break    except (NoSuchWindowException, NoSuchElementException):        pass

我没有意识到,当我单击打开表单时,另一个窗口在后台非常短暂地打开,然后关闭。这将window_handles增加到2,因此执行与等待2个窗口句柄有关的任何操作仍然会引发错误。

c# – .NET Selenium NoSuchElementException; WebDriverWait.Until()不起作用

c# – .NET Selenium NoSuchElementException; WebDriverWait.Until()不起作用

我们有一个.NET 4.5,MVC,C#项目.我们正在使用Selenium进行UI测试,测试会在我们有wait.Until()的行上间歇性地失败.一个这样的例子是:

NoSuchElementException was unhandled by user code
An exception of type 'OpenQA.Selenium.NoSuchElementException' occurred in WebDriver.dll but was not handled in user code
Additional information: Unable to locate element: {"method":"css selector","selector":"#assessment-472 .status-PushedToSEAS"}

它就在这里抛出:

Thread.Sleep(600);
wait.Until(drv => drv.FindElement(By.CssSelector("#" + assessmentQueueId + " .status-PushedToSEAS")));

我可以看到浏览器打开,我看到它到达那一点,我可以检查元素以查看元素是否存在.它的id完全正确.

我们有这个问题很多,到目前为止解决方案是在它前面抛出Thread.Sleep(600)(或类似的时间). wait.Until()的重点是不必这样做,这使我们的测试套件变得非常长.另外,正如您在上面的示例中所看到的,有时我们甚至在将Thread.Sleep()放在它前面之后也会遇到问题,我们必须延长时间.

为什么.NET Selenium的WebDriver.Until()不起作用,并且有一种不同的方式来做同样的事情而不需要等待一段时间?同样,问题是间歇性的,这意味着它有时只会发生,它可能发生在任何数量的wait.Until()语句中,而不仅仅是显示的那个!

编辑:

这是一个类变量.
私人WebDriver等等;

它实例化如下:

this.wait = new webdriverwait(driver,TimeSpan.FromSeconds(10));

解决方法

我决定不使用webdriverwait.Until(),而是在主驱动程序上使用隐式等待:

driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));

为了给我这个想法,我在一个不同的问题上充分赞扬了this answer.

OpenQA.Selenium.NoSuchElementException:没有这样的元素:无法定位元素 C# 按类查找

OpenQA.Selenium.NoSuchElementException:没有这样的元素:无法定位元素 C# 按类查找

如何解决OpenQA.Selenium.NoSuchElementException:没有这样的元素:无法定位元素 C# 按类查找?

Message: 
Test method CFSSOnlineBanking.SmokeTests.Transferdisplay threw exception: 
OpenQA.Selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":"#menuLeftRailContainer > div:nth-child(1) > div:nth-child(3)"}
  (Session info: chrome=91.0.4472.164)

Stack Trace: 
RemoteWebDriver.UnpackAndThrowOnError(Response errorResponse)
RemoteWebDriver.Execute(String driverCommandToExecute,Dictionary`2 parameters)
RemoteWebDriver.FindElement(String mechanism,String value)
RemoteWebDriver.FindElementByCssSelector(String cssSelector)
<>c__displayClass23_0.<CssSelector>b__0(ISearchContext context)
By.FindElement(ISearchContext context)
RemoteWebDriver.FindElement(By by)
TransferPage.get_TransferLink() line 22
SmokeTests.Transferdisplay() line 57

我目前正在尝试单击位于 div 内的 href。无论我尝试什么,似乎都无法点击它。

enter image description here

这是我检查时的元素。

enter image description here

我尝试添加等待 我尝试通过 LinkText、PartialLinkText、cssSelector 和 xPATH 单击

目前我在 TransferPage 类中有这个:

public IWebElement TransferLink => _driver.FindElement(By.CssSelector("#menuLeftRailContainer > div:nth-child(1) > div:nth-child(3)"));

然后在我的实际测试方法中:

_driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(15);
transferPage.TransferLink.Click();

解决方法

您可以尝试以下方法吗

xpath :

//a[@href=''/connect-native/transfer/'']

或 css 选择器

a[href=''/connect-native/transfer/''] 

在代码中:

public IWebElement TransferLink => _driver.FindElement(By.CssSelector("a[href=''/connect-native/transfer/'']"));

因为您在代码中使用的 css 选择器看起来有点乱。你确定有 1/1 匹配的元素吗?

如果这不起作用,您能在您的网页中查找 iframe 吗?

org.openqa.selenium.InvalidCookieDomainException:使用Selenium和WebDriver禁止文档访问Cookie

org.openqa.selenium.InvalidCookieDomainException:使用Selenium和WebDriver禁止文档访问Cookie

如何解决org.openqa.selenium.InvalidCookieDomainException:使用Selenium和WebDriver禁止文档访问Cookie?

此错误消息…

org.openqa.selenium.InvalidCookieDomainException: Document is cookie-averse

……意味着非法企图在与当前文档不同的域下设置cookie。

细节

具体根据HTML的生活标准规范一个Document Object可被归类为在以下情况下一个Cookie规避文档对象:

  • 没有的文件 。
  • URL方案不是网络方案的文档。

深潜

对于无效的cookie域,当您访问不喜欢cookie的文档(例如本地磁盘上的文件)时,可能会发生此错误。

举个例子:

  • 样例代码:
        from selenium import webdriver
    from selenium.common import exceptions

    session = webdriver.Firefox()
    session.get("file:///home/jdoe/document.html")
    try:
        foo_cookie = {"name": "foo", "value": "bar"}
        session.add_cookie(foo_cookie)
    except exceptions.InvalidCookieDomainException as e:
        print(e.message)
  • 控制台输出:
    InvalidCookieDomainException: Document is cookie-averse
    

如果您已存储来自域的example.comcookie, 通过webdriver会话将这些存储的cookie 推送到任何其他不同的域,例如example.edu。存储的Cookie只能在中使用example.com。此外,要在将来自动登录用户,您只需要存储一次Cookie,即用户登录后的时间。在添加Cookie之前,您需要浏览到收集Cookie的相同域。

例如,一旦用户在应用程序中登录,就可以存储cookie,如下所示:

    from selenium import webdriver
    import pickle

    driver = webdriver.Chrome()
    driver.get(''http://demo.guru99.com/test/cookie/selenium_aut.PHP'')
    driver.find_element_by_name("username").send_keys("abc123")
    driver.find_element_by_name("password").send_keys("123xyz")
    driver.find_element_by_name("submit").click()
# storing the cookies
pickle.dump( driver.get_cookies() , open("cookies.pkl","wb"))
driver.quit()

稍后,如果您希望用户自动登录,则需要先浏览到特定的域/ url,然后必须添加cookie,如下所示:

    from selenium import webdriver
    import pickle

    driver = webdriver.Chrome()
    driver.get(''http://demo.guru99.com/test/cookie/selenium_aut.PHP'')

    # loading the stored cookies
    cookies = pickle.load(open("cookies.pkl", "rb"))
    for cookie in cookies:
        # adding the cookies to the session through webdriver instance
        driver.add_cookie(cookie)
    driver.get(''http://demo.guru99.com/test/cookie/selenium_cookie.PHP'')

解决方法

我正在尝试将Cookie推送到上一个会话存储的Selenium firefox webdriver,但出现错误:

org.openqa.selenium.InvalidCookieDomainException: Document is cookie-averse

我阅读了此HTML Standard
Cookie规章
,一点也不懂。

因此,问题是如何将cookie推送到上一个存储的webdriver会话中?

org.openqa.selenium.NoSuchWindowException的实例源码

org.openqa.selenium.NoSuchWindowException的实例源码

项目:domui    文件:WebDriverConnector.java   
/**
 * Wait for the window handle to disappear.
 * @throws Exception
 */
public void waitForHandleNotPresent() throws Exception {
    try {
        timed(getWaitTimeout(),getWaitInterval(),new Action<Boolean>() {
            @Override
            @Nullable
            public Boolean execute() throws Exception {
                if(!driver().getwindowHandles().contains(driver().getwindowHandle())) {
                    return null;
                }
                return Boolean.FALSE;
            }
        });
    } catch(NoSuchWindowException e) {
        //Already gone,fine!
    }
}
项目:kc-rice    文件:WebDriverAftBase.java   
protected void closeAndQuitWebDriver() {
    if (driver != null) {
        if (WebDriverUtils.dontTearDownPropertyNotSet() && WebDriverUtils.dontTearDownOnFailure(isPassed())) {
            try {
                acceptAlertIfPresent();
                driver.close();
            } catch (NoSuchWindowException nswe) {
                System.out.println("NoSuchWindowException closing WebDriver " + nswe.getMessage());
            } finally {
                if (driver != null) {
                    driver.quit();
                }
            }
        }
    } else {
        System.out.println("WebDriver is null for " + this.getClass().toString() + " if using a remote hub did you include the port?");
    }
}
项目:kc-rice    文件:JiraIssueCreation.java   
private void closeAndQuitWebDriver() {
    if (driver != null) {
        if (WebDriverUtils.dontTearDownPropertyNotSet() && WebDriverUtils.dontTearDownOnFailure(passed)) {
            try {
                driver.close();
            } catch (NoSuchWindowException nswe) {
                System.out.println("NoSuchWindowException closing WebDriver " + nswe.getMessage());
            } finally {
                if (driver != null) {
                    driver.quit();
                }
            }
        }
    } else {
        System.out.println("WebDriver is null for " + this.getClass().toString());
    }
}
项目:kc-rice    文件:JenkinsJsonJobResultsBase.java   
protected void closeAndQuitWebDriver() {
    if (driver != null) {
        if (WebDriverUtils.dontTearDownPropertyNotSet() && WebDriverUtils.dontTearDownOnFailure(passed)) {
            try {
                driver.close();
            } catch (NoSuchWindowException nswe) {
                System.out.println("NoSuchWindowException closing WebDriver " + nswe.getMessage());
            } finally {
                if (driver != null) {
                    driver.quit();
                }
            }
        }
    } else {
        System.out.println("WebDriver is null for " + this.getClass().toString());
    }
}
项目:automation-test-engine    文件:CaseRunner.java   
/**
 * Tear down.
 */
@AfterMethod(alwaysRun = true)
public void tearDown() {
    try {
        if (null != mainDriver) {
            mainDriver.quit();
        }
        if (null != context) {

            Map<String,IMyWebDriver> myWebDrivers = context
                    .getBeansOfType(IMyWebDriver.class);
            for (IMyWebDriver myWebDriver2 : myWebDrivers.values()) {
                WebDriver weD = myWebDriver2.getWebDriver();
                if (null != weD)
                    weD.quit();
            }
        }
    } catch (UnreachablebrowserException | NoSuchWindowException e) { // nopMD
        // browser has been closed,no action needs to be done here.
    }
    if (null != context) {
        ((ConfigurableApplicationContext) context).close();
    }

}
项目:automation-test-engine    文件:MultiWindowsHandler.java   
private void checkCloseWindowAlert(String winh)
        throws NoAlertPresentException {
    try {
        Alert alt = getDriver().switchTo().alert();
        if (alt == null)
            throw GlobalUtils.createInternalError("web driver");
        PopupPromptDialog aDialog = new PopupPromptDialog(getDriver(),alt,alerts.size());
        aDialog.setClosingWindowHandle(winh);
        alerts.add(aDialog);
    } catch (UnreachablebrowserException error) {
        if (getNumberOfOpenWindows() > 0)
            throw GlobalUtils
                    .createInternalError("ATE multi windows handler",error);
    } catch (UnsupportedOperationException e) {

            throw GlobalUtils
                    .createInternalError("Driver doesn't support alert handling yet",e);
    } catch (NoSuchWindowException windClosedAlready) {
        //do nothing if window closed without alert dialog intervention. for example in Chrome.
        throw new NoAlertPresentException(windClosedAlready);
    }
}
项目:rice    文件:WebDriverAftBase.java   
protected void closeAndQuitWebDriver() {
    if (driver != null) {
        if (WebDriverUtils.dontTearDownPropertyNotSet() && WebDriverUtils.dontTearDownOnFailure(isPassed())) {
            try {
                acceptAlertIfPresent();
                driver.close();
            } catch (NoSuchWindowException nswe) {
                System.out.println("NoSuchWindowException closing WebDriver " + nswe.getMessage());
            } finally {
                if (driver != null) {
                    driver.quit();
                }
            }
        }
    } else {
        System.out.println("WebDriver is null for " + this.getClass().toString() + " if using a remote hub did you include the port?");
    }
}
项目:rice    文件:JiraIssueCreation.java   
private void closeAndQuitWebDriver() {
    if (driver != null) {
        if (WebDriverUtils.dontTearDownPropertyNotSet() && WebDriverUtils.dontTearDownOnFailure(passed)) {
            try {
                driver.close();
            } catch (NoSuchWindowException nswe) {
                System.out.println("NoSuchWindowException closing WebDriver " + nswe.getMessage());
            } finally {
                if (driver != null) {
                    driver.quit();
                }
            }
        }
    } else {
        System.out.println("WebDriver is null for " + this.getClass().toString());
    }
}
项目:rice    文件:JenkinsJsonJobResultsBase.java   
protected void closeAndQuitWebDriver() {
    if (driver != null) {
        if (WebDriverUtils.dontTearDownPropertyNotSet() && WebDriverUtils.dontTearDownOnFailure(passed)) {
            try {
                driver.close();
            } catch (NoSuchWindowException nswe) {
                System.out.println("NoSuchWindowException closing WebDriver " + nswe.getMessage());
            } finally {
                if (driver != null) {
                    driver.quit();
                }
            }
        }
    } else {
        System.out.println("WebDriver is null for " + this.getClass().toString());
    }
}
项目:darcy-webdriver    文件:TakeScreenshottest.java   
@SuppressWarnings("unchecked")
@Test
public void shouldThrowFindableNotPresentExceptionIfdriverIsNotPresent() throws IOException {
    TargetedWebDriver driver = mock(TargetedWebDriver.class);
    OutputStream outputStream = mock(OutputStream.class);
    browser browser = new WebDriverbrowser(driver,new StubWebDriverParentContext(),new StubWebDriverElementContext());

    when(driver.getScreenshotAs(OutputType.BYTES))
            .thenThrow(NoSuchWindowException.class);
    try {
        browser.takeScreenshot(outputStream);
        fail("Expected FindableNotPresentException to be thrown");
    } catch (Exception e) {
        assertthat("Expected FindableNotPresentException to be thrown",e.getClass(),equalTo(FindableNotPresentException.class));
    }

    verify(outputStream).close();
}
项目:robotframework-seleniumlibrary-java    文件:WindowManager.java   
protected static void selectMatching(WebDriver webDriver,Matcher matcher,String error) {
    String startingHandle = null;
    try {
        startingHandle = webDriver.getwindowHandle();
    } catch (NoSuchWindowException e) {
        // Window of current WebDriver instance is already closed
    }

    for (String handle : webDriver.getwindowHandles()) {
        webDriver.switchTo().window(handle);
        if (matcher.match(getCurrentwindowInfo(webDriver))) {
            return;
        }
    }

    if (startingHandle != null) {
        webDriver.switchTo().window(startingHandle);
    }
    throw new SeleniumLibraryNonFatalException(error);
}
项目:robotframework-seleniumlibrary-java    文件:WindowManager.java   
public static List<List<String>> getwindowInfos(WebDriver webDriver) {
    String startingHandle = null;
    try {
        startingHandle = webDriver.getwindowHandle();
    } catch (NoSuchWindowException e) {
        // Window of current WebDriver instance is already closed
    }

    List<List<String>> windowInfos = new ArrayList<List<String>>();
    try {
        for (String handle : webDriver.getwindowHandles()) {
            webDriver.switchTo().window(handle);
            windowInfos.add(getCurrentwindowInfo(webDriver));
        }
    } finally {
        if (startingHandle != null) {
            webDriver.switchTo().window(startingHandle);
        }
    }
    return windowInfos;
}
项目:robotframework-selenium2library-java    文件:WindowManager.java   
protected static void selectMatching(WebDriver webDriver,String error) {
    String startingHandle = null;
    try {
        startingHandle = webDriver.getwindowHandle();
    } catch (NoSuchWindowException e) {
        // Window of current WebDriver instance is already closed
    }

    for (String handle : webDriver.getwindowHandles()) {
        webDriver.switchTo().window(handle);
        if (matcher.match(getCurrentwindowInfo(webDriver))) {
            return;
        }
    }

    if (startingHandle != null) {
        webDriver.switchTo().window(startingHandle);
    }
    throw new Selenium2LibraryNonFatalException(error);
}
项目:robotframework-selenium2library-java    文件:WindowManager.java   
public static List<List<String>> getwindowInfos(WebDriver webDriver) {
    String startingHandle = null;
    try {
        startingHandle = webDriver.getwindowHandle();
    } catch (NoSuchWindowException e) {
        // Window of current WebDriver instance is already closed
    }

    List<List<String>> windowInfos = new ArrayList<List<String>>();
    try {
        for (String handle : webDriver.getwindowHandles()) {
            webDriver.switchTo().window(handle);
            windowInfos.add(getCurrentwindowInfo(webDriver));
        }
    } finally {
        if (startingHandle != null) {
            webDriver.switchTo().window(startingHandle);
        }
    }
    return windowInfos;
}
项目:marathonv5    文件:JavaDriverTest.java   
public void windowThrowsExceptionWhenNotExisting() throws Throwable {
    driver = new JavaDriver();
    SwingUtilities.invokeAndWait(new Runnable() {
        @Override public void run() {
            frame.setVisible(true);
        }
    });
    try {
        driver.switchTo().window("My Dialog1");
        throw new MissingException(NoSuchWindowException.class);
    } catch (NoSuchWindowException e) {
    }
}
项目:webtester2-core    文件:FocusSetterTest.java   
@Test
void switchingToWindowByUnkNownNameOrHandleThrowsException() {
    NoSuchWindowException exception = mock(NoSuchWindowException.class);
    when(webDriver.switchTo().window("fooBar")).thenThrow(exception);
    assertThrows(NoSuchWindowException.class,() -> {
        cut.onWindow("fooBar");
    });
    verify(events).fireExceptionEvent(exception);
    verifyNoMoreInteractions(events);
}
项目:webtester-core    文件:WebDriverbrowserTest.java   
@Test(expected = NoSuchWindowException.class)
public void testExceptionHandlingInCaseAWindowIsNotFoundForTheGivennameOrHandle() {

    TargetLocator locator = mockTargetLocator();
    NoSuchWindowException exception = createSeleniumExceptionOfClass(NoSuchWindowException.class);
    doThrow(exception).when(locator).window(NAME_OR_HANDLE);

    try {
        cut.setFocusOnWindow(NAME_OR_HANDLE);
    } finally {
        verifyLastEventFiredWasExceptionEventOf(exception);
    }

}
项目:hsac-fitnesse-fixtures    文件:SeleniumHelper.java   
public int getCurrentTabIndex(List<String> tabHandles) {
    try {
        String currentHandle = driver().getwindowHandle();
        return tabHandles.indexOf(currentHandle);
    } catch (NoSuchWindowException e) {
        return -1;
    }
}
项目:cinnamon    文件:SwitchToWindowImpl.java   
private WebDriver nth(final int zeroBasedindex) {
    try {
        final List<String> windowHandles = webDriver.getwindowHandles().stream().collect(Collectors.toList());
        return webDriver.switchTo().window(windowHandles.get(zeroBasedindex));
    } catch (indexoutofboundsexception e) {
        throw new NoSuchWindowException(e.getMessage(),e);
    }
}
项目:cinnamon    文件:SwitchToWindowImpl.java   
@Override
public WebDriver byTitle(final String title) {
    try {
        final FluentWait<WebDriver> wait = new webdriverwait(webDriver,defaultTimeout().getSeconds());
        return wait.until(windowToBeAvailableAndSwitchToIt(title));
    } catch (TimeoutException e) {
        throw new NoSuchWindowException(String.format("Cannot find the window with title %s.",title));
    }
}
项目:cinnamon    文件:SwitchToWindowImpl.java   
@Override
public WebDriver byPartialTitle(final String partialTitle) {
    try {
        final FluentWait<WebDriver> wait = new webdriverwait(webDriver,defaultTimeout().getSeconds());
        return wait.until(windowToBeAvailableAndSwitchToIt(partialTitle,true));
    } catch (TimeoutException e) {
        throw new NoSuchWindowException(String.format("Cannot find the window with partial title %s.",partialTitle));
    }
}
项目:automation-test-engine    文件:AbstractLockProtectedMultiWindowsHandler.java   
private void removeClosedWindows() {

        boolean winRemoved = false;// nopMD
        String currentWinHandle = "";
        try {
            currentWinHandle = this.getDriver().getwindowHandle();
        } catch (NoSuchWindowException NowinEx) {
            winRemoved = true;
        }
//      for (int i = 0; i < windows.size(); i++) {
//          if (windows.get(i).isClosed()) {
//              windows.remove(i);
//              winRemoved = true;// nopMD
//          }
//      }
        for (Iterator<browserWindow> winItr=windows.iterator(); winItr.hasNext();) {
            browserWindow bw = winItr.next();
            if (bw.isClosed()) {
                winItr.remove();
                winRemoved = true;
            } else {
                try {
                    this.getDriver().switchTo().window(bw.getwindowHandle());
                } catch (NoSuchWindowException NowinE) {
                    winItr.remove();
                    winRemoved = true;
                }
            }
        }
        if (winRemoved) {
            this.getDriver().switchTo()
                    .window(windows.get(windows.size() - 1).getwindowHandle());
        } else {
            this.getDriver().switchTo().window(currentWinHandle);
        }
    }
项目:automation-test-engine    文件:browserWindow.java   
/**
 * Close.
 */
public void close() {
    try {
        obtainWindowFocus();
        myWd.getWebDriverInstance().close();
        this.setClosed(true);
    } catch (NoSuchWindowException NowinE) {
        this.setClosed(true);
    }
}
项目:darcy-webdriver    文件:WebDriverTargets.java   
private String findWindow(TargetLocator targetLocator) {
    for (String windowHandle : targetLocator.defaultContent().getwindowHandles()) {
        browser forWindowHandle = By.id(windowHandle).find(browser.class,parentContext);

        view.setContext(forWindowHandle);

        if (view.isLoaded()) {
            return windowHandle;
        }
    }

    throw new NoSuchWindowException("No window in driver found which has " + view + " "
            + "currently loaded.");
}
项目:darcy-webdriver    文件:WebDriverTargets.java   
private String findWindow(TargetLocator targetLocator) {
    for (String windowHandle : targetLocator.defaultContent().getwindowHandles()) {
        if (targetLocator.window(windowHandle).getTitle().equals(title)) {
            return windowHandle;
        }
    }

    throw new NoSuchWindowException("No window in driver found which has title: " + title);
}
项目:darcy-webdriver    文件:WebDriverTargets.java   
private String findWindow(TargetLocator targetLocator) {
    for (String windowHandle : targetLocator.defaultContent().getwindowHandles()) {
        if (urlMatcher.matches(targetLocator.window(windowHandle).getcurrenturl())) {
            return windowHandle;
        }
    }

    throw new NoSuchWindowException("No window in driver found which has url matching: " + urlMatcher);
}
项目:darcy-webdriver    文件:WebDriverbrowser.java   
/**
 * Wrapper for interacting with a targeted driver that may or may not actually be present.
 */
private void attempt(Runnable action) {
    try {
        action.run();
    } catch (NoSuchFrameException | NoSuchWindowException | NoSuchSessionException e) {
        throw new FindableNotPresentException(this,e);
    }
}
项目:darcy-webdriver    文件:WebDriverbrowser.java   
/**
 * Wrapper for interacting with a targeted driver that may or may not actually be present.
 * Returns a result.
 */
private <T> T attemptAndGet(supplier<T> action) {
    try {
        return action.get();
    } catch (NoSuchFrameException | NoSuchWindowException | NoSuchSessionException e) {
        throw new FindableNotPresentException(this,e);
    }
}
项目:darcy-webdriver    文件:ViewWebDriverTargetTest.java   
@Test(expected = NoSuchWindowException.class)
public void shouldThrowNoSuchWindowExceptionIfViewIsNotLoadedInAnyWindow() {
    View view = new NeverLoadedView();

    WebDriverTarget target = WebDriverTargets.withViewLoaded(view,context);

    target.switchTo(locator);
}
项目:carina    文件:DriverHelper.java   
public void switchWindow() throws NoSuchWindowException {
    WebDriver drv = getDriver();
    Set<String> handles = drv.getwindowHandles();
    String current = drv.getwindowHandle();
    if (handles.size() > 1) {
        handles.remove(current);
    }
    String newTab = handles.iterator().next();
    drv.switchTo().window(newTab);
}
项目:SilkAppDriver    文件:MultiWindowTests.java   
@Test(expected = NoSuchWindowException.class)
public void testSwitchToInvalidWindow() {
    assertEquals(1,driver.getwindowHandles().size());

    driver.switchTo().window("42");
}
项目:darcy-webdriver    文件:WindowUrlWebDriverTargetTest.java   
@Test(expected = NoSuchWindowException.class)
public void shouldThrowNoSuchWindowExceptionIfNowindowsCanBeFoundMatchingTheUrlMatcher() {
    WebDriverTarget target = WebDriverTargets.windowByUrl(equalTo("awesome window"));

    target.switchTo(locator);
}
项目:darcy-webdriver    文件:WindowTitleWebDriverTargetTest.java   
@Test(expected = NoSuchWindowException.class)
public void shouldThrowNoSuchWindowExceptionIfNowindowsCanBeFoundWithTitle() {
    WebDriverTarget target = WebDriverTargets.windowByTitle("awesome window");

    target.switchTo(locator);
}
项目:selendroid    文件:MultipleWebviewHandlingTests.java   
@Test(expected = NoSuchWindowException.class)
public void shouldThrowExceptionIfContextNotFound() {
  openMultipleWebViewActivity();
  SelendroidDriver driver = driver();
  driver.context("BANANA");
}
项目:webtester2-core    文件:FocusSetter.java   
/**
 * Sets the browser's focus to the window with the given name or handle.
 * <p>
 * <b>Tip:</b> A handle for the current window can be got by using the {@link Currentwindow#getHandle()} method.
 *
 * @param nameOrHandle the name or handle of the window to focus on
 * @throws NoSuchWindowException in case there is no window with the given name or handle
 * @see browser#currentwindow()
 * @see Currentwindow#getHandle()
 * @see WebDriver.TargetLocator#window(String)
 * @since 2.0
 */
public void onWindow(String nameOrHandle) throws NoSuchWindowException {
    ActionTemplate.browser(browser())
        .execute(browser -> doOnWindow(browser,nameOrHandle))
        .fireEvent(browser -> new SwitchedToWindowEvent(nameOrHandle));
    log.debug("focused on window with name or handle: {}",nameOrHandle);
}

关于通过Python3使用Selenium和WebDriver切换选项卡时,“ NoSuchWindowException:没有这样的窗口:窗口已经关闭”的问题我们已经讲解完毕,感谢您的阅读,如果还想了解更多关于c# – .NET Selenium NoSuchElementException; WebDriverWait.Until()不起作用、OpenQA.Selenium.NoSuchElementException:没有这样的元素:无法定位元素 C# 按类查找、org.openqa.selenium.InvalidCookieDomainException:使用Selenium和WebDriver禁止文档访问Cookie、org.openqa.selenium.NoSuchWindowException的实例源码等相关内容,可以在本站寻找。

本文标签: