selenium 验证元素是否存在_Selenium WebDriver - 测试元素是否存在

本文介绍了多种使用Selenium WebDriver来验证网页元素是否存在的方法,包括findElements、隐式和显式等待、异常处理等。通过这些技术,开发者可以更高效地检查所需元素是否加载成功,从而编写更稳定的自动化测试脚本。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

赞同来自:

使用findElements而不是findElement。

如果未找到匹配的元素而不是异常,findElements将返回一个空列表。

要检查元素是否存在,您可以尝试这样做

Boolean isPresent = driver.findElements(By.yourLocator).size() > 0如果找到至少一个元素,则返回true,如果不存在则返回false。

赞同来自:

我在Java中找到的最简单的方法是:

List linkSearch= driver.findElements(By.id("linkTag"));

int checkLink=linkSearch.size();

if(checkLink!=0){ //do something you want}

尝试这个:

调用此方法并传递3个参数:

WebDriver变量。 //假设driver_variable为驱动程序。

您要检查的元素。应该从By方法提供。 // ex:By.id(“id”)

以秒为单位的时间限制。

示例:waitForElementPresent(driver,By.id(“id”),10);

public static WebElement waitForElementPresent(WebDriver driver, final By by, int timeOutInSeconds) {

WebElement element;

try{

driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS); //nullify implicitlyWait()

WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds);

element = wait.until(ExpectedConditions.presenceOfElementLocated(by));

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); //reset implicitlyWait

return element; //return the element

} catch (Exception e) {

e.printStackTrace();

}

return null;

}

赞同来自:

我会使用类似的东西(使用Scala [旧的代码“好”Java 8可能与此类似]):

object SeleniumFacade {

def getElement(bySelector: By, maybeParent: Option[WebElement] = None, withIndex: Int = 0)(implicit driver: RemoteWebDriver): Option[WebElement] = {

val elements = maybeParent match {

case Some(parent) => parent.findElements(bySelector).asScala

case None => driver.findElements(bySelector).asScala

}

if (elements.nonEmpty) {

Try { Some(elements(withIndex)) } getOrElse None

} else None

}

...

}那么,

val maybeHeaderLink = SeleniumFacade getElement(By.xpath(".//a"), Some(someParentElement))

赞同来自:

您可以通过在try catch语句之前缩短selenium超时来使代码运行得更快。

我使用以下代码来检查元素是否存在。

protected boolean isElementPresent(By selector) {

selenium.manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS);

logger.debug("Is element present"+selector);

boolean returnVal = true;

try{

selenium.findElement(selector);

} catch (NoSuchElementException e){

returnVal = false;

} finally {

selenium.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);

}

return returnVal;

}

public static WebElement FindElement(WebDriver driver, By by, int timeoutInSeconds)

{

WebDriverWait wait = new WebDriverWait(driver, timeoutInSeconds);

wait.until( ExpectedConditions.presenceOfElementLocated(by) ); //throws a timeout exception if element not present after waiting seconds

return driver.findElement(by);

}

那个简单地查找元素并确定它是否存在的私有方法怎么样:

private boolean existsElement(String id) {

try {

driver.findElement(By.id(id));

} catch (NoSuchElementException e) {

return false;

}

return true;

}这将非常容易,并且可以完成工作。

编辑:你甚至可以更进一步,将By elementLocator作为参数,如果你想通过id以外的东西找到元素,就可以解决问题。

赞同来自:

您可以尝试隐式等待:`

WebDriver driver = new FirefoxDriver();

driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));

driver.Url = "http://somedomain/url_that_delays_loading";

IWebElement myDynamicElement = driver.FindElement(By.Id("someDynamicElement"));`

或者您可以尝试显式等待:`

IWebDriver driver = new FirefoxDriver();

driver.Url = "http://somedomain/url_that_delays_loading";

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));

IWebElement myDynamicElement = wait.Until((d) =>

{

return d.FindElement(By.Id("someDynamicElement"));

});`

显式将在某个操作之前检查元素是否存在。可以在代码中的每个位置调用隐式等待。例如,在一些AJAX操作之后。

您可以在SeleniumHQ页面找到更多信息:http://docs.seleniumhq.org/docs/04_webdriver_advanced.jsp

赞同来自:

public boolean isElementDisplayed() {

return !driver.findElements(By.xpath("...")).isEmpty();

}

赞同来自:

public boolean isElementFound( String text) {

try{

WebElement webElement = appiumDriver.findElement(By.xpath(text));

System.out.println("isElementFound : true :"+text + "true");

}catch(NoSuchElementException e){

System.out.println("isElementFound : false :"+text);

return false;

}

return true;

}

赞同来自:

这对我有用:

if(!driver.findElements(By.xpath("//*[@id='submit']")).isEmpty()){

//THEN CLICK ON THE SUBMIT BUTTON

}else{

//DO SOMETHING ELSE AS SUBMIT BUTTON IS NOT THERE

}

就个人而言,我总是寻求上述答案的混合,并创建一个可重复使用的静态实用程序方法,该方法使用size()< 0建议:

public Class Utility {

...

public static boolean isElementExist(WebDriver driver, By by) {

return driver.findElements(by).size() < 0;

...

}这是整洁,可重复使用,可维护......所有那些好东西;-)

我遇到过同样的问题。对我来说,根据用户的权限级别,页面上不会显示某些链接,按钮和其他元素。我的套件的一部分是测试缺少应该丢失的元素。我花了好几个小时试图解决这个问题。我终于找到了完美的解决方案。

这样做,告诉浏览器查找指定的任何和所有元素。如果它导致0,则表示未找到基于规范的元素。然后我让代码执行一个if语句让我知道它没有找到。

这是在C#中,因此需要对Java进行翻译。但不应该太难。

public void verifyPermission(string link)

{

IList adminPermissions = driver.FindElements(By.CssSelector(link));

if (adminPermissions.Count == 0)

{

Console.WriteLine("User's permission properly hidden");

}

}根据您的测试需要,您还可以选择其他路径。

以下代码段正在检查页面上是否存在非常特定的元素。根据元素的存在,我有测试执行if else。

如果元素存在并显示在页面上,我有console.write告诉我并继续。如果有问题的元素存在,我无法执行我需要的测试,这是需要设置它的主要原因。

如果元素不存在,并且未显示在页面上。我在else中执行了测试。

IList deviceNotFound = driver.FindElements(By.CssSelector("CSS LINK GOES HERE"));

//if the element specified above results in more than 0 elements and is displayed on page execute the following, otherwise execute whats in the else statement

if (deviceNotFound.Count > 0 && deviceNotFound[0].Displayed){

//script to execute if element is found

} else {

//Test script goes here.

}我知道我对OP的回应有点迟了。希望这有助于某人!

这应该这样做:

try {

driver.findElement(By.id(id));

} catch (NoSuchElementException e) {

//do what you need here if you were expecting

//the element wouldn't exist

}

使用Java编写以下函数/方法:

代理人的地方0

在断言期间使用适当的参数调用方法。

赞同来自:

如果你在ruby中使用rspec-Webdriver,你可以使用这个脚本,假设一个元素应该真的不存在而且它是一个通过的测试。

首先,首先从类RB文件中编写此方法

class Test

def element_present?

begin

browser.find_element(:name, "this_element_id".displayed?

rescue Selenium::WebDriver::Error::NoSuchElementError

puts "this element should not be present"

end

end然后,在您的spec文件上,调用该方法。

before(:all) do

@Test= Test.new(@browser)

end

@Test.element_present?.should == nil如果您的元素不存在,您的规范将通过,但如果元素存在,则会抛出错误,测试失败。

赞同来自:

要查找特定元素是否存在,我们必须使用findElements()方法而不是findElement()。

int i=driver.findElements(By.xpath(".......")).size();

if(i=0)

System.out.println("Element is not present");

else

System.out.println("Element is present");这对我有用..

建议我,如果我错了..

赞同来自:

提供我的代码片段。因此,以下方法检查页面上是否存在随机Web元素“创建新应用程序”按钮。请注意,我已将等待时间用作0秒。

public boolean isCreateNewApplicationButtonVisible(){

WebDriverWait zeroWait = new WebDriverWait(driver, 0);

ExpectedCondition c = ExpectedConditions.presenceOfElementLocated(By.xpath("//input[@value='Create New Application']"));

try {

zeroWait.until(c);

logger.debug("Create New Application button is visible");

return true;

} catch (TimeoutException e) {

logger.debug("Create New Application button is not visible");

return false;

}

}

赞同来自:

我发现这适用于Java:

WebDriverWait waiter = new WebDriverWait(driver, 5000);

waiter.until( ExpectedConditions.presenceOfElementLocated(by) );

driver.FindElement(by);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值