首页 > 解决方案 > 引发超时异常的警报处理代码

问题描述

我有下面的代码,它会抛出一个 WebDriverTimeoutException (见控制台截图)。程序是 C#-Selenium-Visual Studio。该代码的目的是在控制台上显示弹出警报文本,然后接受警报。超时发生在第 28 行/wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.AlertIsPresent()); 我将等待时间增加到 15 秒,添加了 try-catch 块(原始代码是 try 块末尾被注释掉的代码块),并添加了 WaitHelpers 但仍然出现此错误。

在此处输入图像描述

using System;
using System.Collections.Generic;
using System.Text;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using System.Threading;
using OpenQA.Selenium.Support.UI;
using SeleniumExtras.WaitHelpers;

namespace EnvironmentSetup
{
    class SpecialElements

{
    static IWebDriver driver = new ChromeDriver();
    
    static void Main()
    {
        string url = "https://www.lambdatest.com/blog/selenium-c-tutorial-handling-alert-windows/";
        driver.Navigate().GoToUrl(url);
        Thread.Sleep(3000);
        try
        {
            WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(20));                             
            wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.AlertIsPresent());
            //wait.Until(ExpectedConditions.AlertIsPresent());
            Thread.Sleep(10000);
            // Switch the control of 'driver' to the Alert from main Window
            IAlert simpleAlert = driver.SwitchTo().Alert();

            // '.Text' is used to get the text from the Alert
            String alertText = simpleAlert.Text;
            Console.WriteLine("Alert text is " + alertText);

            // '.Accept()' is used to accept the alert '(click on the Ok button)'
            simpleAlert.Accept();


            /*alert = driver.SwitchTo().Alert();
            Thread.Sleep(3000);
            Console.WriteLine("Lambda site alert popup text is " + alert.Text);
            Thread.Sleep(3000);
            alert.Accept();
            */
        }

        catch(NoSuchElementException)
        {
            Console.WriteLine("Lambda popup not found");
        }

        driver.Quit();

}}} 

标签: c#selenium-webdrivervisual-studio-codealerttimeoutexception

解决方案


推荐阅读