How to move to ELSE condition if element is not visible in IF in selenium - selenium

I am writing a piece of code in which in the if condition I am giving a condition that if the element is displayed they only go to if part otherwise if the element is not displayed then it should go to else part. But whenever it is coming to the if condition, it searches for the element and when it doesn't find it, it gives a timeout exception. What can be done ?
public void addaddress() {
suites.setupEnviroment();
WebDriver driver = suites.getWebDriver();
try {
//code to find elements
try {
if(driver.findElement(By.xpath("//div[#class='toast lgksToast ']")).isDisplayed()){
System.out.println("fail");
}
else{
System.out.println("pass");
}
} catch (Exception e) {
System.out.println(e);
}
}catch(Exception e) {
System.out.println(e);
}
}
In the above code if element with this xpath (//div[#class='toast lgksToast ']) is not found then its not executing else part
what should i do for thid please suggest.
Thanks in advance

Use the size() method with findElements and it will start working.
if(driver.findElements(By.xpath("//div[#class='toast lgksToast ']")).size() > 0) {
System.out.println("fail");
} else {
System.out.println("pass");
}

Related

How do I click on an element that appears sometimes 1 or sometimes 2 at different intervals

I have done this
List<WebElement> element= driver.findElements(By.xpath(""));
for(int i=0;element.size();i++)
{
driver.findElements(By.xpath("")).isDisplayed();
driver.findElements(By.xpath("")).click();
}
I am new to java and selenium , so I thought of doing this. Is this logic correct or am I wrong? If wrong(most probably) , can you please rectify and explain alongside , wud be very helpful.
I get element not interactable error on this.
In case you are looking for method to wait for one of two elements to appear and then to click on the appeared element you can use this method:
public String waitForOneOfTwoElements(String xpath1, String xpath2){
wait = new WebDriverWait(driver, 30);
try {
wait.until(ExpectedConditions.or(ExpectedConditions.visibilityOfElementLocated(By.xpath(xpath1)),
ExpectedConditions.visibilityOfElementLocated(By.xpath(xpath2))));
if(waitForElementToBeVisible(xpath1)){
return xpath1;
}else if(waitForElementToBeVisible(xpath2)){
return xpath2;
}
}catch (Throwable t){
return null;
}
}
Where waitForElementToBeVisible is:
public boolean waitForElementToBeVisible(String xpath) {
wait = new WebDriverWait(driver, 30);
try {
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(xpath)));
return true;
}catch (Throwable t) {
return false;
}
}
Now, when you get the appeared element you can simply click it with:
String appearedElementXpath = waitForOneOfTwoElements(xpath1,xpath2);
driver.findElement(By.xpath(appearedElementXpath)).click();

Checking a button with TestNG

I am new to the Selenium .
I need to check the availability of a button in the system and need to mark it pass and fail with AssertEquals.
Please help me .
#Test
public void sellercheck () throws InterruptedException
{
Thread.sleep(2000);
driver.findElement(By.id("UserEvent")).click();
//String r=Read.getvalue().get(0);
//select the seller
driver.findElement(By.id("LegacyNumberCriterion")).sendKeys("123456");
driver.findElement(By.id("SuperUse")).click();
System.out.println("seller number entered");
try
{
if(driver.findElements(By.id("OrganizationBranchId")).size()!=0)
{
driver.findElement(By.id("button1")).click();
}
else
{
System.out.println("The button is not available for the seller");
}
}
catch(NoSuchElementException e)
{
System.out.println("Element does not exist!");
}
}
You can choose from following 2 solutions which suitable to you:
1] Code to check element present or not using assertion in Selenium Webdriver would be something like this:
assertTrue(!isElementPresent(By.id("id of button")));
2] This assertion verifies that there are no matching elements in the DOM and returns the value of Zero, so the assertion passes when the element is not present. Also it would fail if it was present.
Assert.assertEquals(0, driver.findElement(By.id("id of button")).size());
Try this solution and let me know if it works.
Try this piece of code with some simple tweaks to your own code:
WebDriver driver;
#Test
public void sellercheck () throws InterruptedException
{
Thread.sleep(2000);
driver.findElement(By.id("UserEvent")).click();
//String r=Read.getvalue().get(0);
//select the seller
driver.findElement(By.id("LegacyNumberCriterion")).sendKeys("123456");
driver.findElement(By.id("SuperUse")).click();
System.out.println("seller number entered");
try
{
if(driver.findElements(By.id("OrganizationBranchId")).size()!=0)
{
driver.findElement(By.id("button1")).click();
}
else
{
System.out.println("The button is not available for the seller");
}
}catch(NoSuchElementException e)
{
System.out.println("Element does not exist!");
}
}
Let me know if this works for you or update me the error you see.

Selenium Testing : If element is not present then exception is not handled by Exception of type NoSuchElementException in Selenium

If any element doesnot exists in Selenium Testing, then I am unable to handle it. I have tried this code.
public static bool IsElementPresent(IWebDriver driver, By by)
{
try
{
driver.FindElement(by);
return true;
}
catch (NoSuchElementException)
{
return false;
}
catch (Exception ex)
{
return false;
}
}
It shows timeout exception takes too much time more than 1 min and finally handled by main Exception class, but my automation testing stops, And I dont want to stop my testing.
I have tried this code snippet also.
public bool IsElementPresent(IWebDriver driver, By by, TimeSpan? timeSpan)
{
bool isElementPresent = false;
try
{
if (timeSpan == null)
{
timeSpan = TimeSpan.FromMilliseconds(2000);
}
var driverWait = new WebDriverWait(driver, (TimeSpan)timeSpan);
driverWait.IgnoreExceptionTypes(typeof(WebDriverTimeoutException));
isElementPresent=driverWait.Until(x => x.FindElements(by).Any());
return isElementPresent;
}
catch (NoSuchElementException nex)
{
return false;
}
catch (Exception ex)
{
return false;
}
}
What should I do so that in small span of time it returns true or false.
Another option would be something like
return driver.FindElements(by).length > 0;
I generally use the Displayed property. I use the page object model with pre-determined IWebElements in the example below:
public bool IsPageObjectPresent(IWebElement PageObject)
{
try
{
if (PageObject.Displayed)
{
Console.WriteLine("Element is displayed");
return true;
}
else
{
Console.WriteLine("Element present but not visible");
return true;
}
}
catch (NoSuchElementException)
{
Console.WriteLine("Element not present");
return false;
}
catch (StaleElementReferenceException)
{
Console.WriteLine("Stale element present");
return false;
}
}
try{
// Add your complete portion of code here //
System.out.println("Portion of code executed Successfully");
}
catch(Exception name)
{
System.out.println("Portion of code failed");
}
Please try and let me know.......

Webdriver taking too much time to execute the script in if block using java

While executing the code when the webelement "err" is null then webdriver taking too much time for executing the if block but "err" is not null webdriver going to the else block and driver getting closed then ok
driver.findElement(By.id("UHID")).sendKeys("1234440");
driver.findElement(By.id("btnSubmit")).click();
Thread.sleep(100);
WebElement err=null;
try
{
err=driver.findElement(By.xpath("//*[#id='Error']/div/p"));
}
catch(NoSuchElementException e)
{
System.out.println("No Such Element Exception.");
}
if(!(err != null && err.isDisplayed()))
{
Thread.sleep(100);
Select policytype=new Select(driver.findElement(By.id("PolicyType")));
policytype.selectByVisibleText("Corporate");
//Select Payer
Thread.sleep(200);
driver.findElement(By.id("Payer")).sendKeys(Keys.TAB);
//Payer
Select Payer=new Select(driver.findElement(By.id("Payer")));
Payer.selectByIndex(1);
driver.findElement(By.id("Submit")).click();
}
else
{
System.out.println("UHID Not Exist");
driver.close();
}
please advise
thanks in advance
try this:
try
{
driver.manage().timeouts().implicitlyWait(1000, TimeUnit.MILLISECONDS);
err=driver.findElement(By.xpath("//*[#id='Error']/div/p"));
}
catch(NoSuchElementException e)
{
//Log your error
}
finally
{
driver.manage().timeouts().implicitlyWait(15000, TimeUnit.MILLISECONDS);
}
This will tell the driver to only take 1 second to search for the "err" element before throwing an exception. It will also reset the implicit wait, even in the event of an exception.

selenium web driver should stop execution of last element

I am new to selenium and was trying to make my work automated. My results consists of pagination like next page. At last page "Next" button is disabled and my code should not access that particular element.
List<WebElement> pagesize = driver.findElements(By.xpath("html/body/div[1]/div[3]/div[3]/div/span"));
while(true) {
for(int i=5; i<=pagesize.size(); i++) {
WebElement Analystelem = driver.findElement(By.xpath("html/body/div[1]/div[3]/div[3]/div["+i+"]/span"));
List<WebElement> pagesize = driver.findElements(By.xpath("html/body/div[1]/div[3]/div[3]/div/span"));
System.out.println(pagesize.size());
while(true) {
for(int i=5;i<=pagesize.size();i++) {
WebElement Analystelem = driver.findElement(By.xpath("html/body/div[1]/div[3]/div[3]/div["+i+"]/span"));
if(elementpage.isEnabled()) {
elementpage.click();
}
else {
System.exit(1);
}
note: older search is the next button here.
at last page of results i am getting an exception as
"Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"xpath","selector":"html/body/div[1]/div[3]/div[3]/div[10]/span"}"
First of all I doubt that you have searched for a span and stored its reference to 'Analystelem' but you are calling a click action on 'elementpage'.
If the code you provided is working than below given code will work fine. When Selenium will find the element and tries to click on it; it will throw exception, handle the exception as you feel best but it will not break your execution.
Just put your code in Try Catch block like this:
while(true)
{
for(int i=5;i<=pagesize.size();i++)
{
WebElement Analystelem=driver.findElement(By.xpath("html/body/div[1]/div[3]/div[3]/div["+i+"]/span"));
if(elementpage.isEnabled())
{
Try
{
elementpage.click();
}
Catch (Exception ex)
{
//Do whatever you want to do here
}
}
else
{
System.exit(1);
}
}
}
Additionally, you do not have to check weather the element is enabled or not. Let the try catch do its work. More suited code:
while(true)
{
for(int i=5;i<=pagesize.size();i++)
{
WebElement Analystelem=driver.findElement(By.xpath("html/body/div[1]/div[3]/div[3]/div["+i+"]/span"));
Try
{
elementpage.click();
}
Catch (Exception ex)
{
System.exit(1);
//Do whatever you want to do here
}
}
}