1
using System;
using OpenQA.Selenium;

namespace MyApplication.Selenium.Tests.Source
{
    public sealed class MyExpectedConditions
    {

        private void ExpectedConditions()
        {
        }

        public static Func<IWebDriver, IAlert> AlertIsPresent()
        {
            return (driver) =>
            {
                try
                {
                    return driver.SwitchTo().Alert();
                }
                catch (NoAlertPresentException)
                {
                    return null;
                }
            };
        }

    }
}

你可以像这样使用它:

new WebDriverWait(Driver, TimeSpan.FromSeconds(5)) { Message = "Waiting for alert to appear" }.Until(d => MyExpectedConditions.AlertIsPresent());
Driver.SwitchTo().Alert().Accept();
4

1 回答 1

5

WebDriverWaitWebDriverTimeoutException如果在所需的等待期内未找到警报,将抛出异常。

使用 try catch 块WebDriverWait来 catch WebDriverTimeoutException

我使用如下扩展方法:

public static IAlert WaitGetAlert(this IWebDriver driver, int waitTimeInSeconds = 5)
{
    IAlert alert = null;

    WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(waitTimeInSeconds));

    try 
    {
        alert = wait.Until(d =>
            {
                try
                {
                    // Attempt to switch to an alert
                    return driver.SwitchTo().Alert();
                }
                catch (NoAlertPresentException)
                {
                    // Alert not present yet
                    return null;
                }
            });
    }
    catch (WebDriverTimeoutException) { alert = null; }

    return alert;
}

并像这样使用它:

var alert = this.Driver.WaitGetAlert();
if (alert != null)
{
    alert.Accept();
}
于 2013-10-06T21:56:30.997 回答