首页 > 解决方案 > 如何使用 C# 和 Selenium 处理简单的警报?

问题描述

这是我的代码,当它到达时Switchto().Alert()出现错误提示“没有这样的警报”

            driver.FindElement(By.XPath("(.//*[normalize-space(text()) and normalize-space(.)='Add Document'])[1]/following::button[1]")).Click();

            **driver.SwitchTo().Alert().Accept();**

            var signFrame = driver.FindElement(By.Id("hsEmbeddedFrame"));
            driver.SwitchTo().Frame(signFrame);


            driver.FindElement(By.XPath("(.//*[normalize-space(text()) and normalize-space(.)='Istrong textnitials'])[1]/preceding::li[1]")).Click();strong text

标签: c#seleniumselenium-webdriveralert

解决方案


您可能需要等待警报存在才能单击它:

using OpenQA.Selenium.Support.UI;


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

// alert is present will automatically switch to the alert
wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.AlertIsPresent());

// the below line is no longer necessary
// driver.SwitchTo().Alert().Accept();

如果这仍然抛出NoSuchAlertException,那么出现的弹出窗口可能不是真正的警报,而是可能是 HTML 模式——在这种情况下,您可以检查它并使用 Selenium 找到合适的选择器来接受它。


推荐阅读