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

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.

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();

How to move to ELSE condition if element is not visible in IF in 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");
}

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.

I am not able to switch to IFrame using Internet Explorer

I have developed a s keyword driven framework. It has a action keyword to switch the frame.
It works fine with Mozilla. But when it comes to IE it is not switching. It logs error.
IE driver -IEDriverServer_x64_2.44.0
IE version -9
Selenium version -selenium-java-2.44.0
Thanks in advance.
public static void switchFrame(String object,String data)throws Exception{
try{
driver.switchTo().frame("Ifrm");
Log.info("Switched the frame");
}
catch(Exception e){
Log.error("Not able to switch the frame--- " + e.getMessage());
DriverScript.bResult = false;
}
}
Here exception occurs.
I assume, the value you specified in frame is id/name/etc. You have to access the frame by calling the driver with specified value. Code would be
driver.switchTo().frame(driver.findElement(By.id("Ifrm")));
Selenium won't let me switch to the iframe by ID on Internet Explorer, but it does allow me to switch by index. If you have some sort of property that you can check that it is only available on the iframe you can do the following
new WebDriverWait(driver, 5).until(
new Predicate<WebDriver>() {
#Override
public boolean apply(WebDriver input) {
try {
int i = 1;
while (true) {
driver.switchTo().defaultContent();
driver.switchTo().frame(i);
String aClass =
driver.findElement(By.xpath("/html/body"))
.getAttribute("class");
if (aClass.contains("modal")) {
return true;
}
++i;
}
} catch (NoSuchFrameException e) {
return false;
}
}
}
);
In my case I was looking for a body class of modal

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
}
}
}