gpt4 book ai didi

c# - Selenium C# 使用 PageObject 检查 IWebElement 是否存在

转载 作者:太空宇宙 更新时间:2023-11-03 15:02:57 26 4
gpt4 key购买 nike

目标:使用 PageObject 检查当前页面上是否存在元素/IWebElement。

我知道你可以使用类似的东西:

IWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(3));
IWebElement element = wait.Until(ExpectedConditions.ElementExists(By.Id("foo")));

但是当我使用 PageObjects 时,我不想再次使用 id/xpath 等。我目前正在使用下面的方法来检查元素是否存在。但是为了快速做到这一点,我首先设置了隐式等待,然后将其重置为默认值。它工作得很好,但感觉很脏。

我发现了一些其他较旧的帖子。但这还没有为我提供任何解决方案。希望对您有所帮助!

页面对象:

        [FindsBy(How = How.Id, Using = "errorMessage")]
public IWebElement btnSubmit { get; set; }

调用方法:

CheckElementExists(errorMessage))

方法;

public bool CheckElementExists(IWebElement pageObject)
{
Browser.getDriver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(100);
try
{
return pageObject.Equals(pageObject);
}
catch (NoSuchElementException)
{
return false;
}
finally
{
Browser.getDriver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(30);
}
}

最佳答案

我没有使用 C# 的经验,但我认为它与 JAVA 非常相似,因此您可以在 C# 中转换以下 JAVA 代码。

如果只想编写函数来检查元素是否存在,这就是您可以做到的。

public boolean isElementExisit(WebElement element){
try{
element.getTagName();
return true;
}catch (NoSuchElementException){
return false;
}
}

如果你想写一些需要等待的东西,那么你可以使用流畅的等待。

public void waitUntilElementIsPresent(WebElement element, int timeout){
Wait wait = new FluentWait<WebDriver>(driver)
.withTimeout(timeout, TimeUnit.SECONDS)
.pollingEvery(5, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);

wait.until(new Function() {
@Override
public Boolean apply(Object o) {
element.getTagName();
return true;
}
});
}

关于c# - Selenium C# 使用 PageObject 检查 IWebElement 是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45238065/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com