在 Selenium 中使用等待元素可点击方法的随机错误 [英] Random errors using wait for element clickable method in Selenium
问题描述
我有一个自定义的等待方法定义为:
I have a custom wait method defined as:
public IWebElement WaitForElementClickable(IWebDriver _driver, By elementName)
{
var wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(20));
return wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementToBeClickable(elementName))
}
我有一个地方可以让我点击一个按钮并加载一个新页面,它停留在正在加载"状态.几秒钟(2-3 秒),然后我想在加载后单击其他内容....
I have one place where I click on a button and a new page loads, it sticks on "loading" for a few seconds (2-3 secs) and then I want to click on something else once it loads....
public void enterSearchInfo()
{
//Thread.Sleep(2000);
IWebElement selectElement = utility.WaitForElementClickable(_driver, element);
selectElement.Click();
}
即使我将等待方法设置为 20 秒,这也只能在 10 次中起作用 5 次,另外 5 次我收到以下错误...
Even though I have the wait method set to 20 secs this only works 5 times out of 10, the other 5 times I get the following error...
OpenQA.Selenium.ElementClickInterceptedException: element click intercepted:
当我取消注释 Thread.Sleep(2000)
时,它可以运行 10 次 10 次
When I uncomment Thread.Sleep(2000)
it works 10 out of 10 times
有没有比 wait for element clickable
方法更好的方法来处理这个问题?我宁愿不在我的代码中硬编码睡眠等待.
Is there a better way to handle this than the wait for element clickable
method? I'd rather not be hardcoding sleep waits in my code.
推荐答案
这是我在我创建的框架中使用的.它吃掉 ElementClickInterceptedException
和 StaleElementReferenceException
并一直尝试直到超时或成功.它摆脱了很多问题,比如你所说的.还有其他特定于每个页面的方法,但我发现这在大量场景中非常有效.
This is what I use in a framework I've created. It eats ElementClickInterceptedException
and StaleElementReferenceException
and keeps trying until the timeout or success. It got rid of a lot of issues like what you are talking about. There are other ways to do it specific to each page but I found that this works really well in a large number of scenarios.
/// <summary>
/// Clicks on an element
/// </summary>
/// <param name="locator">The locator used to find the element.</param>
/// <param name="timeOut">[Optional] How long to wait for the element (in seconds). The default timeOut is 10s.</param>
public void Click(By locator, int timeOut = 10)
{
DateTime now = DateTime.Now;
while (DateTime.Now < now.AddSeconds(timeOut))
{
try
{
new WebDriverWait(Driver, TimeSpan.FromSeconds(timeOut)).Until(ExpectedConditions.ElementToBeClickable(locator)).Click();
return;
}
catch (ElementClickInterceptedException)
{
// do nothing, loop again
}
catch (StaleElementReferenceException)
{
// do nothing, loop again
}
}
throw new Exception($"Unable to click element <{locator}> within {timeOut}s.");
}
这篇关于在 Selenium 中使用等待元素可点击方法的随机错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!