Reputation: 59
I have a step in my test that goes into several html pages and looks for an element on the screen. That element can have 2 different CSS class names while looking the same in the website (visually speaking) , I have to use an if statement with a logical 'or' to identify them
if (Status == driver.findElement(By.cssSelector(".inlineblock.redClockBigIcon.middle.isOpenExchBig-2")) || Status == driver.findElement(By.cssSelector(".inlineblock.redClockBigIcon.middle.isOpenExchBig-1")));
System.out.println("Stock is closed");)
I expected that if one of the 2 elements would appear, the Eclipse would
recognize it. Well - The second element out of the 2 appeared - and for some reason I've got an exception error. The if statement gave attention only to the first condition in the if, and ignored the second.
org.openqa.selenium.NoSuchElementException: no such element:
locate element: {"method":"css selector","selector":".inlineblock.redClockBigIcon.middle.isOpenExchBig-2"}Unable to
How can I make the || to work in this 'if' statement? Thanks
Upvotes: 0
Views: 820
Reputation: 2115
You can try using try catch
block:
boolean isFirstElemPresent = true;
try{
driver.findElement(By.cssSelector(".inlineblock.redClockBigIcon.middle.isOpenExchBig-1"));
}catch (NoSuchElementException e){
isFirstElemPresent = false;
}
if(isFirstElemPresent == false)
driver.findElement(By.cssSelector(".inlineblock.redClockBigIcon.middle.isOpenExchBig-2"));
Or
To avoid try catch
block, use below code snap:
List<WebElement> elements = driver.findElements(By.className("redClockBigIcon"));
if (elements.size() == 0) {
System.out.println("Element is not present");
} else {
System.out.println("Element is present");
}
Upvotes: 0
Reputation: 1991
In your above logic, you have Status
which is an already existing WebElement
that you're comparing against another Webelement
that you're looking up. I don't think this is what your intention was so I'm going to make some assumptions in a solution.
First: Find all of the elements that might exist with your desired selector (Note I'm using findElements
instead of findElement
)
List<WebElement> clockIconThingies = driver.findElements(By.cssSelector(".inlineblock.redClockBigIcon.middle.isOpenExchBig-2, .inlineblock.redClockBigIcon.middle.isOpenExchBig-1"));
Second: Check if that found anything
if(clockIconThingies.size() > 0)
{
System.out.println("Stock is closed");
}
Alternatively for your css selector, from the image it looks like you might not need to do an or at all and just look for the class redClockBigIcon
like this:
List<WebElement> clockIconThingies = driver.findElements(By.cssSelector(".redClockBigIcon"));
Upvotes: 1