Wait until text is not present in textbox selenium - java

Below is the scenario I am trying to automate:
1) Some text is already present in Textbox.
2) Click on Radio button.
3) Processing popup is displayed for few seconds. After popup disappears the textbox
becomes blank
4) After textbox is blank then I have to enter different value in text box.
Please help me, how to wait till textbox value is blank.
I am automating with IE driver.
Thanks In advance

I would try:
int timeout = 10; // depends on your needs
WebDriverWait myWait= new WebDriverWait(driver,timeout);
myWait.until(ExpectedCondition.textToBePresentInElementValue(By locator, String text))
-- with empty string passed as text argument

You can try something like this :-
public void waitUntilTextNotToBeInWebElement(WebElement element, String textValue) {
int timer = 0;
final int pollInterval = 500;
while (timer < MAX_TIME*1000) {
if (element.getText().equalsIgnoreCase(textValue)) {
sleep(500);
timer += pollInterval;
} else {
return;
}
}
throw new TimeoutException("Maximum time exceeded.");
}

Hi there is two possible way through which you can do this
1.Use Expected condition
// after you have clicked on radio button and it does some processing
WebDriverWait wait = new WebDriverWait(driver,30);
wait.until(ExpectedConditions.invisibilityOfElementWithText(locator, "your text"));
// now perform your operation
use if else
// get the text of input box like below
String myInitialText = driver.findElement(By.xpath("")).getAttribute("value");
// click on radio button
// now apply the logic
if(myInitialText == null){
System.out.println("Input box is blank");
// perform next operation
}else{
Thread.sleep(5000);
}
// now fill the input box

Below code worked for me.
WebElement element=driver.findElement(By.id("ctl00_cphClaimFlow_tabcontainerClaimFlow_tabFulfillment_Shipping_ctl33_txtStreeAddress1"));
String myInitialText=element.getAttribute("value");
//click on radio btn
driver.findElement(By.id("ctl00_cphClaimFlow_tabcontainerClaimFlow_tabFulfillment_Shipping_ctl33_radNewAddress")).click();
logger.info("New Address radio button clicked");
System.out.println("1 "+myInitialText);
while(!myInitialText.equals("")){
try {
Thread.sleep(5000);
logger.info("Thread is sleeping");
//System.out.println("2 "+myInitialText);
myInitialText=driver.findElement(By.id("ctl00_cphClaimFlow_tabcontainerClaimFlow_tabFulfillment_Shipping_ctl33_txtStreeAddress1")).getAttribute("value");
//System.out.println("3 "+myInitialText);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
driver.findElement(By.id("ctl00_cphClaimFlow_tabcontainerClaimFlow_tabFulfillment_Shipping_ctl33_txtStreeAddress1")).sendKeys(td.getAddressLine1().get(0));
logger.info("Address Line1 entered");

Related

(JAVA) Selenium - Could not find / detect element in while loop

I need help in JAVA Selenium. I could not get the web driver to find the element I want in a while loop. I tried to do it without while loop, it would work. However without the while loop, I could not make the web driver to reload the page while waiting for the element to load. I would really appreciate if anyone could assist me in this.
The problem with my code is it will not exit the loop since elementProgress is forever FALSE because the web driver is not detecting the button thus not updating the elementProgress boolean value.
//check if progress button exist
boolean elementProgress;
elementProgress = driver.findElements(By.cssSelector("tr:nth-child(1) .iconLabel")).size() != 0;
//auto reload page to prevent webpage timeout
while (!elementProgress) {
TimeUnit.SECONDS.sleep(15);
driver.navigate().refresh();
boolean check_dl_queue = driver.findElements(By.cssSelector(".cell > .table .total_records")).size() != 0;
if (!check_dl_queue) {
driver.navigate().refresh();
}
Thread.sleep(1500);
driver.navigate().refresh();
elementProgress = driver.findElements(By.cssSelector("tr:nth-child(1) .iconLabel")).size() != 0;
System.out.println("P2:" + elementProgress); //to printout element status
}
I had found a solution to that, haven't got time to post it here. Below are the the solution.
//boo stat for while loop
boolean elementProgress = true;
boolean elementProgress2 = true;
//setup new web driver wait
WebDriverWait dl_wait = new WebDriverWait(driver, 15);
//auto reload page to prevent webpage timeout
while (elementProgress) {
driver.navigate().refresh();
//start button click
try {
//phase 1: wait for button 1, if exceed wait time goto exception
dl_wait.until(presenceOfElementLocated(By.cssSelector("tr:nth-child(1) .iconLabel")));
retryingFindClick(By.cssSelector("tr:nth-child(1) .iconLabel"));
//phase 2: refresh page after button successfully clicked
driver.navigate().refresh();
//phase 3: wait for button 2, if exceed wait time goto exception
while(elementProgress2) {
try {
dl_wait.until(presenceOfElementLocated(By.cssSelector("tr:nth-child(1) .icon-cancel")));
retryingFindClick(By.cssSelector("tr:nth-child(1) .icon-cancel"));
//exit elementProgress2 while loop
elementProgress2 = false;
} catch(Exception ex) {
//refresh page to counter false positive element not found exception
driver.navigate().refresh();
}
}
//exit elementProgress while loop
elementProgress = false;
} catch(Exception ex) {
//refresh page to counter false positive element not found exception
driver.navigate().refresh();
}
}
public boolean retryingFindClick(By by) {
boolean result = false;
int attempts = 0;
while(attempts < 2) {
try {
driver.findElement(by).click();
result = true;
break;
} catch(StaleElementReferenceException e) {
}
attempts++;
}
return result;
}

WebElement Comparison

In my project, I have several datas with checkboxes if I click those different set of data and try to delete that I am getting two types of alerts: one is "deleted successfully" for one data and for other data it showing "data cannot be deleted" popup. How to handle these both in Selenium?
I used if-else statement compared both webelement string using getText() method but it is showing NoSuchElementException.
Here is my code:
WebElement Popup = driver.findElement(By.Xpath="//input[#class='btn-btn-popup']")
WebElement e = driver.findElement(By.xpath="//div[#text='Deleted successfully']");
String Deletepopup = e.getText();
WebElement f = driver.findElement(By.xpath="//div[#text='Data Cannot be deleted']");
String CannotDeltedPopup = f.getText();
if (Deletepopup.equals("Deleted Successfully")) {
Popup.click();
}
else if (CannotDeletedPopup.equals("Data Cannot be deleted")) {
Popup.click();
}
Of course you get NoSuchElementException. You try to find both WebElements, but you can have present only one at a time.
If your action succeed you will have present this
driver.findElement(By.xpath("//div[#text='Deleted successfully']")) and this driver.findElement(By.xpath("//div[#text='Data Cannot be deleted']")) will throw NoSuchElementException and vice versa for action failed.
In your case I recommend you to use try-catch block.
String txt;
try{
txt = driver.findElement(By.xpath("//div[#text='Deleted successfully']")).getText();
}catch(NoSuchElementException e){
try{
txt = driver.findElement(By.xpath("//div[#text='Data Cannot be deleted']")).getText();
}catch(NoSuchElementException e1){
txt = "None of messages was found"; //this will happend when none of elements are present.
}
}
I this case you will try to find message 'Deleted successfully' and if it is not present will try to find message 'Data Cannot be deleted'.
Also I will recommend you to use Explicit Wait, to give your app some time to look for you element before to throw NoSuchElementException.
String txt;
try{
WebDriverWait wait=new WebDriverWait(driver, 10);
txt = wait.until(ExpectedConditions.visibilityOfElementLocated(
By.xpath("//div[#text='Deleted successfully']"))
).getText();
}catch(NoSuchElementException e){
try{
WebDriverWait wait=new WebDriverWait(driver, 10);
txt = wait.until(ExpectedConditions.visibilityOfElementLocated(
By.xpath("//div[#text='Data Cannot be deleted']"))
).getText();
}catch(NoSuchElementException e1){
txt = "None of messages was found"; //this will happend when none of elements are present.
}
}
This will give 10 seconds time to look for element before to throw NoSuchElementException. You can change this time to how much do you need to increase success of your app.

Selenium check if a window is currently open

So I have a selenium webdriver logging me into a website and from there I click a button which opens a second window. I use this code below to switch to the new window
String winParent = driver.getWindowHandle();
for (String winHandle : driver.getWindowHandles()) {
driver.switchTo().window(winHandle);
}
Now on that second window I run some automation . Once complete I would press the save button and this would close the current window. If the window doesn't close it means I have some errors on the page and I need to loop back and fix it.
driver.findElement(By.id("btnSave")).click();
if (isAlive(driver) == false) {
//break and exit
System.out.println("cic" + name);
finalString = finalString + "cic: " + name;
break;
}
public Boolean isAlive(WebDriver driver) {
try {
driver.getCurrentUrl();//or driver.getTitle();
return true;
} catch (Exception ex) {
return false;
}
}
The The program works as expected when it catches the errors and the window doesn't close. But as soon as everything is clear and the window closes it enters the if statement above and displays this error.
Unable to receive message from renderer.
I believe that I'm not checking if the window has been closed correctly.
edit: after some debugging it seems like once the window closes the program can't really tell what to do next. http://i.imgur.com/l8nsPPr.png
I suggest using windowHandle for this.
You are saving initial window in String winParent = driver.getWindowHandle();
Then you switch to the second window, which will have different handle.
When you need to check if the second window is still open, just use:
private boolean isNewWindowOpened(WebDriver driver, String parentWindowHandle) {
try {
return !driver.getWindowHandle().equals(parentWindowHandle);
} catch (Exception ex) {
driver.switchTo(parentWindowHandle);
return false;
}
I came across the same situation, I've got a solution for you, check window count after clicking on "Save" button. Ideally, there will be one window if you have provided all the correct data and if not then there are two windows.
driver.findElement(By.id("btnSave")).click();
if (driver.getWindowHandled().size() >= 2) {
// make required changes
// again click on save button
} else {
//break and exit
System.out.println("cic" + name);
finalString = finalString + "cic: " + name;
break;
}
}

Visible but overlaid

I am making a script using selenium and at one step it shows loading icon in center of webpage.The loading icon appears after 1st line is executed
test.driver.findElement(By.id("oaapprove")).click();
test.driver.findElement(By.xpath("//*[text()='DATA EXPLORER']")).click();
The 2nd element is still there in DOM but its not clickable so i get error as not clickable
i tried this:
Boolean isPresent=test.driver.findElements(By.xpath("//div[#class='spinner-container']")).size() > 0;
if(isPresent)
{
System.out.println("Target element found");
}
while(test.driver.findElements(By.xpath("//div[#class='spinner-container']")).size() > 0)
{
try {
System.out.println("inside");
Thread.sleep(250);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if(!(test.driver.findElements(By.xpath("//div[#class='spinner-container']")).size() > 0))
{
System.out.println("Target element not found");
}
It is printing "inside" till the loading icon is visible but but after icon disappears it does not print "inside" but it waits for 7-8 secs and then executes next statements.
What is the cause of waiting?
Can u please tell how to i solve this.
try actions class if it's showing using fluentwait that element is clickable:
WebElement yourElement = test.driver.findElement(By.xpath("//*[text()='DATA EXPLORER']"));
Actions act = new Actions(test.driver);
act.moveToElement(yourElement).click().build().perform();
I got the solution and i used stalenessOf
new WebDriverWait(driver, 10).until(ExpectedConditions.stalenessOf(findElement(By.xpath("element_path"))));

How to Handle the Alert Pop Up

I am working on the Web Application, In that Application user need to send the values into
the Search Text Box, then user need to click on the Search Button, If the Value are
avilable in the db, then that value will be display on the another Text Box, If that value
in not in the db, Then Alert Pop up is Displaying on the screen, At that i am using below
code, But it is not working fine.
if(driver.findElement(By.id(APL.MT_ET_Search_Btn_ID)).isEnabled())
{
driver.findElement(By.id(APL.MT_ET_Search_Btn_ID)).click();
System.out.println("Clicked on the Search Button for the Text box");
Thread.sleep(2000);
//Handling the Code
String page = driver.getTitle();
System.out.println(page);
if(page.equals("No Recipients found"));
{
System.out.println("No Recipients found");
driver.switchTo().alert().accept();
System.out.println("Handling the Pop Up");
}
}
You have an error in the second if, remove the semicolon and it will be better.
if(driver.findElement(By.id(APL.MT_ET_Search_Btn_ID)).isEnabled())
{
driver.findElement(By.id(APL.MT_ET_Search_Btn_ID)).click();
System.out.println("Clicked on the Search Button for the Text box");
Thread.sleep(2000);
//Handling the Code
String page = driver.getTitle();
System.out.println(page);
if(page.equals("No Recipients found")) //#############HERE
{
System.out.println("No Recipients found");
driver.switchTo().alert().accept();
System.out.println("Handling the Pop Up");
}
}
Anyway if you please tell us WHY is not working I can check if there can be other problems.

Categories