how to keep the code running when element is not found - java

hi there my code keep running an error when this element is not found
driver.findElement(By.xpath("(//span[#class='_soakw coreSpriteLikeHeartOpen'])")).click();
can anyone help me? i want the other code to keep running even though this element is not found I've been looking for the answer the whole day on the internet

You can place a try catch block around the find element. After the catch blok the execution of the code wil continue.
The function findelement throws a NoSuchElementException when there is no element found.
// Set the timeout for searching an element
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
try
{
// Try to find the element
driver.findElement(By.xpath("(//span[#class='_soakw coreSpriteLikeHeartOpen'])")).click();
}
catch (NoSuchElementException e)
{
System.out.println("Element Not Found");
}
// Continue
Let me know if it worked or if you need anymore help.

You can do this in following way too :
List<WebElement> element= driver.findElements(By.xpath("//span[#class='_soakw coreSpriteLikeHeartOpen']"));
if(element.size()>0)
{
System.out.println("Found");
}
else
{
System.out.println("Not Found");
}
Important :
FindElement() : It throws a NoSuchElementException exception when it
fails to find If the element.
FindElements() : If the element doesn’t exist or not available on
the page then, the return value will be an empty list.

Related

Continue if element not found, if found save it

I have a loop, where I open links one by one. Inside this loop I have the if statement, which checks:
If I see name, then I copy it
If I don't see name, then I ignore it and continue looping.
List<WebElement> demovar = driver.findElements(By.xpath("//*[#id=\"big_icon_view\"]/ul/li/p/a"));
System.out.println(demovar.size());
ArrayList<String> hrefs = new ArrayList<String>();
for (WebElement var : demovar) {
System.out.println(var.getText());
System.out.println(var.getAttribute("href"));
hrefs.add(var.getAttribute("href"));
}
int i = 0;
for (String href : hrefs) {
driver.navigate().to(href);
System.out.println((++i) + ": navigated to URL with href: " + href);
if(driver.findElement(By.xpath("//a[#id='name']")).isDisplayed()) {
System.out.println("I can see Name");
} else {
System.out.println("I cant see Name");
}
Thread.sleep(3000); // To check if the navigation is happening properly.
}
Why is this not working properly? As I assume, it should have the following:
If the element is displayed then I can see Name
else the element is NOT displayed, then I cannot see Name.
I'm not sure what error message you are seeing here, but if your code is not working then it's quite likely the element is not displayed on the page, so you will receive an exception when attempting to locate it.
You can catch the NoSuchElementException to handle the case where the element does not appear on the page.
for (String href : hrefs) {
driver.navigate().to(href);
System.out.println((++i) + ": navigated to URL with href: " + href);
// create isDisplayed variable
boolean isDisplayed = true;
try {
isDisplayed = driver.findElement(By.xpath("//a[#id='name']")).isDisplayed();
}
catch(NoSuchElementException) {
isDisplayed = false;
}
// do something else here with isDisplayed
if (isDisplayed) { System.out.println("I can see Name"); }
else { System.out.println("I can not see Name"); }
}
This code does almost the same thing as yours, but we catch the NoSuchElementException that gets thrown if the element does not appear on the page.
If this does not work for you, feel free to post the error message or results you are seeing in your code, it'll help track down the issue.
API of the findElement(By by) in the Interface WebDriver states the following
"Find the first WebElement using the given method. This method is affected by the 'implicit wait' times in force at the time of execution. The findElement(..) invocation will return a matching row, or try again repeatedly until the configured timeout is reached. findElement should not be used to look for non-present elements, use findElements(By) and assert zero length response instead."
Which means that in case if the element is not found it keeps trying until configured timeout and throws the exception NoSuchElementException - If no matching elements are found
Hence it would be better to handle in the following ways
Using FindElements which returns a list of all WebElements, or an empty list if nothing matches as follows:
if(driver.findElements(By.ByXPath).size()<0)
Using a try/catch/finally to catch the NoSuchElementException and a boolean flag to determine if its present or not. The boolean flag can be set to false in case if exception is caught.
After #Christine help, i did a solution for me
for (String href : hrefs) {
driver.navigate().to(href);
boolean isPresent = driver.findElements(By.xpath("element")).size() > 0;
if (isPresent) {
String test = driver.findElement(By.xpath("element")).getText();
System.out.println(test);
} else {
System.out.println("Name not found");
}
Thread.sleep(3000); // To check if the navigation is happening properly.
}
}
}
And this is working fine =)

Getting an element not found exception from an exception handler

I am getting element not found exception while trying to locate the element in a try loop. Below is my code:
private boolean isPresent(WebDriver driver,String findElement)
{
driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);
try {
driver.findElement(By.xpath(findElement));
return true;
}
catch (NoSuchElementException e) {
return false;
}
finally{
driver.manage().timeouts().implicitlyWait(40,TimeUnit.SECONDS);
}
}
Instead of using find element and timeouts use some waits or until for the element to be present and then do the operation.
eg. This will wait until the element is located, then do what you want to do with your myDynamicELement
WebElement myDynamicElement = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(By.id("myElement")));
It looks like you are trying to validate whether your element is present or not. For that use a logic something like this.
A) Inside try
1) Wait for the element to be present
2) Then Use if then else to check if element present and return true or false
B) Inside Catch handle the error.
The better way to do this is to avoid throwing exceptions in the first place.
private boolean isPresent(WebDriver driver, By locator)
{
return !driver.findElements(locator).isEmpty();
}
Instead of passing the locator as string and requiring XPath, use a By locator. Now you can pass the method any locator type... Id, CSS selector, etc.

How to execute else if(xpathcondition) , If first xpathcondition fails?

if(driver.findElement(By.xpath("//div/h3[contains(text(),'MOVENPICK HOTEL DEIRA')]")).isDisplayed())
{
}
else if(driver.findElement(By.xpath("//div/h3[contains(text(),'HOTEL INN')]")).isDisplayed())
{
}
In the above code, if condition fails means how to execute else if(xpathcondition),
For failed condition its showing exception as "Element not Found". If I handled exception, how to execute else if??
Advance thanks for your help !!
Ideally isDisplayed() should return false instead of throwing exception.
You can go with saifur answer. Another approach would be (as per this)
try {
if(driver.findElement(By.xpath("//div/h3[contains(text(),'MOVENPICK HOTEL DEIRA')]")).isDisplayed())
{ }
}catch(){ //catch executes the else part when the exception is thrown.
if(driver.findElement(By.xpath("//div/h3[contains(text(),'HOTEL INN')]")).isDisplayed())
{ }
}
Check this issue as well
The issue here is if any of the elements look up fails the test will be terminated with NoSuchElement or Element not Found exception since element is not a part of the dom. To avoid this you can trick the code a little bit or do another check to see if the element exists first.
I would rather find the element and match the text instead and perform additional task
// Write a selector that would meet the find both elements
WebElement element = driver.findElement(By.cssSelector("div h3"));
if (element.getText().contains("MOVENPICK HOTEL DEIRA")) {
//do this
} else if (element.getText().contains("HOTEL INN")) {
//do something
} else {
//do nothing and log some error
}

IF statement in Selenium Webdriver

I wonder if someone could help me with an issue I'm having trying to work out and If statement in Java for Webdriver.
When logging into the app I am testing it is possible to be taken to a security questions page before the main page (if a new user etc). What I would like the code in my test to do is if presented with the security questions page fill it in and move on, if not check you are on the main page.
I was able to do this in Selenium RC using
if (selenium.isTextPresent("User Account Credentials Update")) {
selenium.type("//input[#id='securityQuestion']", "A");
selenium.type("//input[#id='securityAnswer']", "A");
selenium.type("//input[#id='emailAddress']", "test#test.com");
selenium.click("update");
selenium.waitForPageToLoad("30000");
}
assertTrue(selenium.isTextPresent("MainPage"));
Playing around with Webdriver I am using:
if(driver.findElement(By.id("securityQuestion")) != 0) {
driver.findElement(By.id("securityQuestion")).sendKeys("A");
driver.findElement(By.id("securityAnswer")).sendKeys("A");
driver.findElement(By.id("emailAddress")).sendKeys("test#test.com");
driver.findElement(By.id("update")).click();
Assert.assertTrue("Main Page is not Showing",
driver.getPageSource().contains("MainPage"));
The Problem with this is is that it always chucks an exception if the Security screen is not displayed. How do I need to set the code so that it ignores the security page stuff if that page is not presented?
Thank you for any help :-)
You can use driver.findElements as a way to check that a specific element is present without having exceptions thrown. This works because it will return a list of size 0 of WebElements if no element is found. At the moment, if Selenium tries to find an element using findElement and the element doesn't exist, it will throw a NoSuchElementException This means you can replace:
if (driver.findElement(By.id("securityQuestion")) != 0)
with this:
if (driver.findElements(By.id("securityQuestion")).size() != 0)
There is actually nothing wrong in an exception being thrown as long as you catch/handle it.
In other words, I'd follow the EAFP approach here:
try {
driver.findElement(By.id("securityQuestion"));
// ...
} catch (NoSuchElementException e) {
// handle exception, may be at least log in your case
}
I usually just wrap it into a method:
public boolean elementExists(By selector)
{
try
{
driver.findElement(selector)
return true;
}
catch(NoSuchElementException e)
{
return false;
}
}

How to handle dynamic xpaths

I need to select the text that has returned based on my search operation.
For every search xpaths will get differ. These are various xpaths that are returned on search
.//*[#id='messageBoxForm']/div/div[1]/div[1]/div/div[1]/div[1]/span/input
.//*[#id='messageBoxForm']/div/div[1]/div[1]/div/div[2]/div/div/div[2]/div[2]/strong
You could place it in a try-catch-block and use the first x-path in your try, catch the "NoSuchElementException" Selenium could throw and then try the other x-path.
Based on the criteria you posted this should do the job.
WebElement element;
try {
element = webDriver.findElement(By.xpath("xyz"));
} catch (NoSuchElementException e) {
element = webDriver.findElement(By.xpath("abc"));
}
... do things with your element

Categories

Resources