我已经在我的测试中为各种事情设置了一些明确的等待但是必须为我的XPath,ID等指定字符串。所以我的页面设置包括像......
public const string ApplyDatasetButton_XPath = "//*[@id='btn_apply_datasets']";
[FindsBy(How = How.XPath, Using = ApplyDatasetButton_XPath)]
public IWebElement ApplyDatasetButton { get; set; }
...然后我在等待的测试中使用它...
SeleniumGetMethods.WaitForElementVisible(By.XPath(ApplyDatasetButton_XPath), 20);
...将等待设置为......
public static void WaitForElementVisible(By element, int timeoutInSeconds)
{
if (timeoutInSeconds > 0)
{
WebDriverWait wait = new WebDriverWait(DriverSetup.driver, TimeSpan.FromSeconds(timeoutInSeconds));
wait.Until(ExpectedConditions.ElementIsVisible(element));
}
}
然而,创建字符串似乎有点矫枉过正,但我无法弄清楚如何使用创建的元素。基本上在C#中有一种方法可以做类似的事情......
[FindsBy(How = How.XPath, Using = "//*[@id='btn_apply_datasets']")]
public IWebElement ApplyDatasetButton { get; set; }
SeleniumGetMethods.WaitForElementVisible(ApplyDatasetButton, 20);
答案 0 :(得分:0)
用于ExpectedConditions的扩展片段,如下所示:
/// <summary>
/// An expectation for checking that an element is present on the DOM of a page
/// and visible. Visibility means that the element is not only displayed but
/// also has a height and width that is greater than 0.
/// </summary>
/// <param name="locator">The locator used to find the element.</param>
/// <returns>The <see cref="T:OpenQA.Selenium.IWebElement" /> once it is located and visible.</returns>
public static Func<IWebDriver, IWebElement> ElementIsVisible(IWebElement element) => driver =>
{
try
{
return ElementIfVisible(element);
}
catch (StaleElementReferenceException)
{
return null;
}
};
private static IWebElement ElementIfVisible(IWebElement element)
{
if (!element.Displayed)
return null;
return element;
}
然后像这样扩展IWebDriver接口
public static IWebElement WaitUntilElementIsVisible(this IWebDriver driver, IWebElement element, int timeOutInSeconds = DefaultTimeoutSeconds)
{
try
{
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeOutInSeconds));
return wait.Until(ExpectedConditions.ElementIsVisible(element)); //Wait finishes when return is a non-null value or 'true'
}
catch (NoSuchElementException ex)
{
MethodLogger.OutputLog($"Element: {element} was not found on current page.");
MethodLogger.OutputLog(ex);
return null;
}
catch (WebDriverTimeoutException)
{
MethodLogger.OutputLog($"Timed out Looking for Clickable Element; {element}: Waited for {timeOutInSeconds} seconds.");
return null;
}
}
用法:
IWebDriver driver = new ChromeDriver();
driver.WaitUntilElementIsVisible(ApplyDatasetButton, 20);