C# 我们可以在同一个程序中进行两次显式等待吗

C# 我们可以在同一个程序中进行两次显式等待吗,c#,selenium,selenium-webdriver,nosuchelementexception,C#,Selenium,Selenium Webdriver,Nosuchelementexception,我在同一个程序中有两次显式等待。一个用于WaitForElement,一个用于WaitForPageLoad。但它似乎不起作用。当我将其中一个更改为隐式等待时,效果很好。否则代码一开始就失败了。selenium初学者不知道为什么失败 错误: NoSuchElementException waits:在两种不同的方法中使用了它们 WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(3)); {

我在同一个程序中有两次显式等待。一个用于WaitForElement,一个用于WaitForPageLoad。但它似乎不起作用。当我将其中一个更改为隐式等待时,效果很好。否则代码一开始就失败了。selenium初学者不知道为什么失败

错误:

 NoSuchElementException
waits:在两种不同的方法中使用了它们

  WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(3));
    {
       IWebElement myDynamicElement = wait.Until<IWebElement>((d) =>
       {
          return d.FindElement(By.ClassName("header"));
       });
       if (myDynamicElement != null) return true;
    }

  WebDriverWait _wait = new WebDriverWait(driver, TimeSpan.FromSeconds(3));
    {
       IWebElement _myDynamicElement = _wait.Until<IWebElement>((d) =>
       {
          return d.FindElement(By.ClassName("header-buttons"));
       });
       if (_myDynamicElement != null) return true;
    }

我认为更通用的等待元素的方法更适合您的使用。因此,请使用通用表达式并传入搜索条件。例如:

public void WaitForElementById(string elementId, int timeout = 5)
{
    //Where '_driver' is the instance of your WebDriver
    WebDriverWait _wait = new WebDriverWait(_driver, new TimeSpan(0, 0, timeout));
    IWebElement element = _wait.Until(x => x.FindElement(By.Id(elementId)));
}
如果等待超时,这将引发异常,因此您还可以添加try/catch以不同方式报告失败。我个人在一个交换机的测试解决方案中使用了它,该交换机对我常用的每种搜索类型都有一个案例。然后我传入搜索类型搜索词(例如,elementAttribute ID,string myTextboxID)


话虽如此,我看不出你的代码有任何明显的错误会导致它无法工作。

在你的第一个代码块中,如果(myDynamicElement!=null)返回true,你的
之后似乎有一个错误
}
行。这是故意的吗?对不起。打错了。我已经编辑了代码。@user1177636,我想在我想等待的地方使用这些方法。我从页面中随机选取了一个类名(标题)并使用了它。因此,当我想等待加载元素时,我使用WaitforElement(By.classname(“something”))。实际上应该在那里使用什么?@user1177636,但是当我在两个不同的方法中使用这两个等待并在程序中调用它们时,它在一开始就失败了。当我将其中一个更改为隐式时,它会工作。异常是在我使用waitforelement(By…)的行中引发的,这是程序中的第二行。当我调用这个等待方法时,它失败了。但是当使用隐式测试时(在第二行中使用相同的wait语句),我尝试了以下代码。。它给出一个ElementNotVisibleException并停止。在显式等待中,“somedynamicelement”是什么意思?代码:返回d.FindElement(By.ClassName(“somedynamicelement”);它是否引用了该页面上的任意类名?
ElementNotVisibleException
表明它已通过您提供的标识符找到元素,但元素本身未设置为对用户可见。这意味着它以某种方式被禁用。不知道你所说的“某个动态事件”是什么意思,写在哪里?在您的代码中?标题和标题按钮。我从seleniumhq.orgIWebDriver=newfirefoxdriver()得到了这个等待;driver.Url=“”;WebDriverWait wait=新的WebDriverWait(驱动程序,TimeSpan.FromSeconds(10));IWebElement myDynamicElement=等待.Until((d)=>{return d.FindElement(By.Id(“someDynamicElement”);});那里的字符串
“someDynamicElement”
引用的是目标元素ID。您应该提供针对那里的任何错误的ID。但是,此代码与我提供的示例相同(至少据我所知)。
public void WaitForElementById(string elementId, int timeout = 5)
{
    //Where '_driver' is the instance of your WebDriver
    WebDriverWait _wait = new WebDriverWait(_driver, new TimeSpan(0, 0, timeout));
    IWebElement element = _wait.Until(x => x.FindElement(By.Id(elementId)));
}