nosuchelementexception在c# selenium中不被用户代码处理

本文关键字:用户 代码 处理 selenium nosuchelementexception | 更新日期: 2023-09-27 17:49:56

我想用显式等待等待我的selenium程序最多30秒(globalvar . timetommaximwait)。但是当它无法定位元素时,它会在wait.until(…)行暂停并显示OpenQA.Selenium。NoSuchElementException未被用户代码处理如果我按继续或按F10,它再次尝试找到元素,并继续相同的我定义的时间垃圾邮件。无法理解为什么程序暂停,而错误信息在两者之间出现。我使用VS2010, c#, selenium 2.45,Ie 9

任何帮助都是非常感谢的。

 public string SetValueInTextBox(string InputData, string xPathVal)
        {
            try
            {
                WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(GlobalVar.timetomaximumwait));
                 wait.Until<IWebElement>((d) =>
                {
                    return d.FindElement(By.XPath(xPathVal));
                });
                 IWebElement TargetElement = driver.FindElement(By.XPath(xPathVal));
               // IWebElement TargetElement = driver.FindElement(By.XPath(xPathVal));

                elementHighlight(TargetElement);
                TargetElement.Clear();
                TargetElement.SendKeys(InputData);
                //driver.FindElement(By.XPath(xPathVal)).SendKeys(InputData);

                return "Pass";
            }
            catch (Exception e)
            {
                return "Fail";
            }
            finally
            {
               // string SSName = "temp.jpg";
                TakeScreenshot("SetValueInTextBox");
            }
        }

nosuchelementexception在c# selenium中不被用户代码处理

问题在这里:

wait.Until<IWebElement>((d) =>
{
    return d.FindElement(By.XPath(xPathVal));
});

你需要处理当找不到元素时抛出的异常。

wait.Until<IWebElement>((d) =>
{
    try
    {
        return d.FindElement(By.XPath(xPathVal));
    }
    catch(NoSuchElementException e)
    {
        return null;
    }
});

我建议在catch块中添加一些日志记录,这样您就知道每次驱动程序无法找到元素。