Selenium Webdriver等待来自另一个元素的元素



我正在尝试使用WebDriverWait来等待面板中的元素加载

WebDriverWait wait = WebDriverWait(MyWebDriver, 10);
By completeButton = By.Id("completeButton");
// This waits on page level and loads the first which isn't always the correct panel.
// How can I wait from a given panel?
IWebElement button = wait.Until(drv => drv.FindElement(completeButton));
button.Click();

我有多个面板,每个面板在准备就绪时都会创建完整的按钮,因此需要等待。

我可以等待整个页面上的元素,但是我希望能够等待来自另一个元素的元素。

查看文档这显然是错误的,但是我可以做类似的事情来等待子页面中的元素,其他人如何解决这个问题?

WebDriverWait wait = WebDriverWait(MyPanelSubElement, 10);

1.创建一个 WebElementWait 类:

public class WebElementWait : DefaultWait<IWebElement>
{       
public WebElementWait(IWebElement element, TimeSpan timeout) : base(element, new SystemClock())
{
this.Timeout = timeout;
this.IgnoreExceptionTypes(typeof(NotFoundException));
}
}

2.现在将其用作:

//Find your target panel . You can use WebDriverWait to lookup this element
//while waiting on webdriver if required.
IWebElement panel  = //some code to get your container panel ;
IWebElement targetButton = new WebElementWait(panel, TimeSpan.FromMilliseconds(10000)).Until(p => { return p.FindElement(By.Id("completeButton")); });
targetButton.Click();

希望这有帮助!!

您可以添加面板部分加载的显式等待。目前,ExpectedConditions已从OpenQA.Selenium.Support.UI中弃用,并在SeleniumExtras.WaitHelpers中新增。请包括以下 NuGet 包

需要添加 NuGet 包:

DotNetSeleniumExtras.WaitHelpers

预期条件将在OpenQA.Selenium.Support.UISeleniumExtras.WaitHelpers中提供。为了避免冲突,您可以将新导入的包赋值到一个变量中,并且可以访问所需的方法。

因此,您可以像这样进行导入(using SeleniumWaitHelper = SeleniumExtras.WaitHelpers;(,并且可以将预期条件作为SeleniumWaitHelper.ExpectedConditions

示例代码:

在这里,系统将等待 10 秒钟,直到MyPanelSubElement可见。

WebDriverWait wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(10));
//DotNetSeleniumExtras.WaitHelpers NuGet package needs to be added
wait.Until(SeleniumWaitHelper.ExpectedConditions.ElementIsVisible(By.Id("Required Element ID")));

编辑:

您可以尝试使用一些 xpath 来等待所需的面板内容部分加载。

我假设您有多个具有相同 Xapth 的面板。请考虑以下示例 HTML

示例 HTML:

<div class="panelContainer">
---------------------
---------------------
<button id="completeButton" class="btn">Complete</button>
-------------------
</div>

您可以参数化面板索引,并根据所需的面板条件对其进行更改。

示例代码:

int panelIndex = 1;
By buttonPath = By.XPath("//div[@class='Panel']["+panelIndex+"]//*[@id='completeButton']");
WebDriverWait wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(10));
wait.Until(SeleniumWaitHelper.ExpectedConditions.ElementIsVisible(buttonPath));

假设,如果要等待第二个面板按钮加载,则更改面板索引,因为 2.It 将等到按钮加载在第二个面板中完成。

相关内容

最新更新