Selenium WebDriver generates StaleElementReferenceExeption on getText() on table elements - selenium

The current environment:
Selenium Server version 2.37.0
RemoteWebDriver running on Firefox
no Ajax / asynchronously loaded content
My tests are attempting to validate the content of each cell of an HTML table. Before accessing any table element an explicit wait verifies that the <tbody> element exists
ExpectedCondition<WebElement> recruitTableIsPresent = ExpectedConditions.presenceOfElementLocated(By.id("newRecruitFieldAgentWidget:newRecruitDataTable_data"));
new WebDriverWait(driver, 5).until(recruitTableIsPresent);
Once the table is verified to exist, data is pulled out by row and column
private Stats[] parseStats() {
String xpath = "//tbody[#id='regionalFieldAgentWidget:regionalDataTable_data']/tr[%d]/td[%d]";
Stats[] stats = new Stats[3];
for (int i = 0; i < stats.length; i++) {
String inProgresOrders = cellContent(xpath, i, 1);
String maxCapacity = cellContent(xpath, i, 2);
String allocationRatio = cellContent(xpath, i, 3);
Stats[i] = new Stats(inProgressORders, maxCapacity, allocationRatio);
}
return stats;
}
private String cellContent(String xpathTemplate, int row, int cell) {
String xpath = String.format(xpathTemplate, row + 1, cell + 1);
new WebDriverWait(driver, 10).until(ExpectedConditions.presenceOfElementLocated(By.xpath(xpath)));
WebElement elementByXPath = driver.findElementByXPath(xpath);
return elementByXPath.getText();
}
I don't see any race conditions, since the table content is populated with the page, and not in an asynchronous call. Additionally, I have seen other answers that suggest invoking findElement() via the driver instance will refresh the cache. Lastly, the explicit wait before accessing the element should ensure that the <TD> tag is present.
What could be causing the getText() method return the following exception:
org.openqa.selenium.StaleElementReferenceException: Element not found in the cache - perhaps the page has changed since it was looked up
It's worthwhile to note that the failure is intermittent. Some executions fail while other passes through the same code pass. The table cell causing the failure are also not consistent.

There is a solution to this using Html-Agility-Pack.
This will work only if you want to read the data from that page.
This goes likes this
//Convert the pageContent into documentNode.
void _getHtmlNode(IWebDriver driver){
var htmlDocument = new HtmlDocument();
htmlDocument.LoadHtml(driver.PageSource);
return htmlDocument.DocumentNode;
}
private Stats[] parseStats(){
String xpath = "//tbody[#id='regionalFieldAgentWidget:regionalDataTable_data']/tr[%d]/td[%d]";
Stats[] stats = new Stats[3];
for (int i = 0; i < stats.Length; i++) {
String inProgresOrders = cellContent(xpath, i, 1);
String maxCapacity = cellContent(xpath, i, 2);
String allocationRatio = cellContent(xpath, i, 3);
Stats[i] = new Stats(inProgressORders, maxCapacity, allocationRatio);
}
return stats;
}
private String cellContent(String xpathTemplate, int row, int cell) {
String xpath = String.format(xpathTemplate, row + 1, cell + 1);
new WebDriverWait(driver, 10).until(ExpectedConditions.presenceOfElementLocated(By.xpath(xpath)));
var documentNode = _getHtmlNode(driver);
var elementByXPath = documentNode.SelectSingleNode(xpath);
return elementByXPath.InnerText;
}
now read any data.
Some tips for using htmlNode.
1. Similar to driver.FindElement: document.SelectSingleNode
2. Similar to driver.FindElements: document.SelectNodes
3. Similar to driver.Text: document.InnerText.
For more search regarding HtmlNode.

Turns out there was a race condition as I've already mentioned. Since jQuery is available via PrimeFaces there is a very handy solution mentioned in a few other posts. I implemented the following method to wait for any asynchronous requests to return before parsing page elements
public static void waitForPageLoad(JavascriptExecutor jsContext) {
while (getActiveConnections(jsContext) > 0) {
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
throw new RuntimeException(ex);
}
}
}
private static long getActiveConnections(JavascriptExecutor jsContext) {
return (Long) jsContext.executeScript("return (window.jQuery || { active : 0 }).active");
}
Each built in driver implementation implements the JavascriptExecutor interface, so the calling code is very straightforward:
WebDriver driver = new FirefoxDriver();
waitForPageLoad((JavascriptExecutor) driver);

Related

Why my selenium function say no Element found

Why if i use same code of affordabilityErrorVerify() in mortgageCalculator() function its working fine but when i use that code in affordabilityErrorVerify() [ same as i posted here ] it says : --> org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":"#ifrm_13536"}
its weird for me can someone help me how i can make it work
public class test1 extends base {
public WebDriver driver;
public static Logger log =LogManager.getLogger(base.class.getName());
#BeforeTest
public void initialize() throws IOException {
driver = initializeDriver(); // initialize the browser driver based on data.properties file browser value
}
#Test(dataProvider = "dataDriven")
public void mortgageCalculator(String amount, String year, String Frequency, String type, String product,
String term, String rate) throws IOException, InterruptedException {
driver.get(prop.getProperty("url")); // read the data.properties file for get the value of url
driver.manage().window().maximize();
LandingPage l = new LandingPage(driver); // created object for Landing page to access page element
Actions actions = new Actions(driver);
WebElement mainMenu = l.menuBar();
actions.moveToElement(mainMenu);
WebElement subMenu = l.clickLink();
actions.moveToElement(subMenu);
actions.click().build().perform();
// Explicit wait because calculator is in frame and it loads after some time
// so wait until frame is visible
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[contains(#class,'col-12 col-md-9 side-content')]")));
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollBy(0,500)");
// switch to frame elements
driver.switchTo().frame(l.switchToFrame());
Thread.sleep(3000);
l.productTabClick().click(); // click on product tab
Thread.sleep(3000);
WebElement money = l.mortgageAmount();
money.click();
money.sendKeys(Keys.CONTROL + "a");
money.sendKeys(Keys.DELETE);
money.sendKeys(amount);
WebElement period = l.mortgageYear();
period.click();
period.sendKeys(Keys.CONTROL + "a");
period.sendKeys(Keys.DELETE);
period.sendKeys(year);
Select s = new Select(l.paymentFrequency());
s.selectByValue(Frequency);
// if data provider send Fixed it will click on fixed radio button otherwise click on variable
if (type == "Fixed") {
l.paymentType().click();
} else {
l.paymentType().click();
}
Select ss = new Select(l.paymentProduct());
ss.selectByValue(product);
Thread.sleep(3000);
driver.switchTo().defaultContent();
js.executeScript("window.scrollBy(0,300)");
driver.switchTo().frame(l.switchToFrame());
Thread.sleep(3000);
WebElement inputOwnRateTerm = l.paymentTerm();
inputOwnRateTerm.click();
inputOwnRateTerm.sendKeys(Keys.CONTROL + "a");
inputOwnRateTerm.sendKeys(Keys.DELETE);
l.paymentTerm().sendKeys(term);
WebElement inputOwnRateValue = l.paymentRate();
inputOwnRateValue.click();
inputOwnRateValue.sendKeys(Keys.CONTROL + "a");
inputOwnRateValue.sendKeys(Keys.DELETE);
l.paymentRate().sendKeys(rate);
inputOwnRateValue.sendKeys(Keys.ENTER);
Thread.sleep(3000);
String actualPayment = l.monthlyPayment().getText();
String actualIOT = l.interestOverTerm().getText();
String actualInterestOverTerm = actualIOT.substring(0, actualIOT.length()-1);
//double actualInterestOverTerm = Math.round(actualIOT)* 10.0) / 10.0;
//System.out.print(actualPayment); // uncomment to see what Mortgage Payment amount function is returning for given data
//System.out.print(actualInterestOverTerm);
//System.out.print(actualIOT);
String totalAmount = amount;
int arg1 = Integer.parseInt(totalAmount);
String mortgageRate = rate;
double arg2 = Double.parseDouble(mortgageRate);
String totalYear = year;
int arg3 = Integer.parseInt(totalYear);
// to find out total Interest over term months based on year
String iot = term;
int iot1 = Integer.parseInt(iot);
int arg4 = iot1 * 12;
// Pass all 4 argument into mortgage calculator to assert actual and expected result
calculator c = new calculator();
double[] expected = c.mortgageCalculator(arg1, arg2, arg3, arg4);
//System.out.println("Mortgage Payment :" + expected[0]); // giving back Mortgage Payment amount from custom function
//System.out.println("Interest over term :" + expected[1]); // giving back Interest over term amount from custom function
NumberFormat defaultFormat = NumberFormat.getCurrencyInstance(); // converting numbers into money format [number format]
String act = defaultFormat.format(expected[1]);
String expectedInterestOverTerm = act.substring(0, act.length()-1);
//***********************
// ActualPayment = Getting value from https://www.coastcapitalsavings.com/calculators/mortgage-calculator
// Expected[0] = Getting value from calculator() function which is mortgageCalculator logic file
//***********************
Assert.assertEquals(actualPayment,defaultFormat.format(expected[0])); // Assertion to find out both values are same
Assert.assertEquals(actualInterestOverTerm,expectedInterestOverTerm); // Assertion to find out both values are same
log.info("*************Expected****************");
log.info("Mortgage Payment :" + expected[0]);
log.info("Interest Over Term :" + expectedInterestOverTerm);
log.info("**************Actual*****************");
log.info("Mortgage Payment :" + actualPayment);
log.info("Interest Over Term :" + actualInterestOverTerm);
log.info("_______________________________________");
}
#Test
public void affordabilityErrorVerify() throws InterruptedException
{
LandingPage l = new LandingPage(driver); // created object for Landing page to access page element
JavascriptExecutor js = (JavascriptExecutor) driver;
Thread.sleep(3000);
driver.switchTo().defaultContent();
js.executeScript("window.scrollBy(0,-500)");
Thread.sleep(3000);
driver.switchTo().frame(l.switchToFrame());
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[contains(#class,'col-12 col-md-9 side-content')]")));
Thread.sleep(3000);
l.affordabilityTabClick().click(); // click on affordability tab
Thread.sleep(3000);
driver.findElement(By.cssSelector("slider-control:nth-child(3) > #slider-container #name")).click();
driver.findElement(By.cssSelector("slider-control:nth-child(3) > #slider-container #name")).sendKeys("10000");
driver.findElement(By.cssSelector("slider-control:nth-child(3) > #slider-container #name")).sendKeys(Keys.ENTER);
}
By looking at your code, I have a probable solution to your problem.
There is no priority defined for tests. So in TestNG, if priority is not defined, the test will get executed in alphabetical order. In this case, affordabilityErrorVerify() test will execute first and then mortgageCalculator().
If I observe affordabilityErrorVerify(), there is no method to open URL like driver.get(url) so no page will get open and it will cause NoSuchElementException
A possible answer can be assigned priority to tests
#Test (priority=1, dataProvider = "dataDriven")
public void mortgageCalculator(String amount, String year, String Frequency, String type, String product,
String term, String rate) throws IOException, InterruptedException {
//code
}
#Test (priority=2)
public void affordabilityErrorVerify() throws InterruptedException
{
//code
}
In this as well you have to make sure actions on second test are continuing on same page where test1 ends.
Modify your tests and actions considering flow of test and it will work
Happy coding~

Selenium not inputting the whole text into a text box

I am using Selenium to clear out the existing Shipping Address fields of a Salesforce Account object and to assign new values. I am coding in C# and running on Visual Studio 2019.
I am getting cases where the textboxes are not getting fully populated.
My code is below.
private string shippingStreet = "56789 Liberty Street"; // 80 character limit
private string shippingCity = "Toronto"; // 40 character limit
private string shippingState = "ON"; // 80 character limit
private string shippingZip = "87654"; // 20 character limit
private string shippingCountry = "Canada"; // 80 character limit
IWebElement shStreet = driver.FindElement(By.XPath("//textarea[#placeholder='Shipping Street']"));
shStreet.Clear();
shStreet.SendKeys(shippingStreet);
IWebElement shCity = driver.FindElement(By.XPath("//input[#placeholder='Shipping City']"));
shCity.Clear();
shCity.SendKeys(shippingCity);
IWebElement shState = driver.FindElement(By.XPath("//input[#placeholder='Shipping State/Province']"));
shState.Clear();
shState.SendKeys(shippingState);
IWebElement shZip = driver.FindElement(By.XPath("//input[#placeholder='Shipping Zip/Postal Code']"));
shZip.Clear();
shZip.SendKeys(shippingZip);
IWebElement shCountry = driver.FindElement(By.XPath("//input[#placeholder='Shipping Country']"));
shCountry.Clear();
shCountry.SendKeys(shippingCountry);
Please see the screenshot.
I fix this issue by adding an extra space after city, state, zip code, and country but I was wondering if there is a better solution.
You can try this method:
Just call it and add the xpath: WaitForElementDisplayed_byXPathTime("//myPath");
WaitForElementDisplayed_byXPathTime
public static void WaitForElementDisplayed_byXPathTime(string value)
{
var wait = new WebDriverWait(Driver, new TimeSpan(0, 0, 30));
wait.Until(webDriver => webDriver.FindElement(By.XPath(value)).Displayed);
}
The other thing I have done on these is create a new type method for individual characters like you would on mobile. This just slows it down a bit.
public static void TypeCharsIndividually(IWebElement element, string expectedValue)
{
//use your code for element displayed and element enabled
element.Click();
element.Clear();
foreach (char c in expectedValue)
{
element.SendKeys(c.ToString());
Thread.Sleep(100);
}
}
java click
public static void ClickJava(IWebElement element)
{
IJavaScriptExecutor executor = driver IJavaScriptExecutor;
executor.ExecuteScript("arguments[0].click();", element);
}
WaitForElement
public static bool WaitForElementDisplayed_byXPath(string path)
{
var result = true;
try { _wait.Until(webDriver => driver.FindElement(By.XPath(path)).Displayed); }
catch (StaleElementReferenceException) { WaitForElementDisplayed_byXPath(path); }
catch (NoSuchElementException) { WaitForElementDisplayed_byXPath(path); }
catch (WebDriverTimeoutException) { result = false; }
return result;
}
This is a Salesforce issue. I see the problem even when i am manually updating a shipping address field and I tab to another field.

Unable to print the Text associated with the li tag

I have a Google Search bar with a drop down and the options are under a UL and the actual ones under the li. I am unable to retrieve the data field of the li, while I am able to retrieve the count. Have tried with the List elements and looping thru it ,but no luck. The drop with all the Options is Not visible.
I have to print the Titles associated with the li using Selenium Web driver.
Below is what I tried:
ul class=classname> xxx – GSA 2 days ago
wb.findElement(By.xpath("<>")).click();
List items = html_list.findElements(By.tagName("li")); System.out.println("The size of the elements is " + items.size()); for(WebElement item : items) { html_list.sendKeys( Keys.DOWN ); //simulate visual movement
wb.manage().timeouts().implicitlyWait(1000, TimeUnit.SECONDS); System.out.println(item.getText());
}
Hypohesis #1: You don't wait for the page to load after the click on line 1. The li elements are in the DOM but they are not completely loaded. You could test the hypothesis by introducing a delay between line 1 and line 2. I have code that I use to wait for page loads but the specifics depend on the JavaScript framework (e.g. jQuery, AngularJs), on the loading spinner implementation and browser readystate. My readystate logic looks like this:
/**
* Wait for browser readystate to be complete. But don't wait forever.
*
* #param webDriver
*/
public void waitForBrowserReadystateComplete(WebDriver webDriver) {
for (int a=0; a<20; a++) {
JavascriptExecutor javascriptExecutor = (JavascriptExecutor) webDriver;
if (javascriptExecutor.executeScript("return document.readyState")
.toString().equals("complete")) {
break;
}
sleepResponsibly(500);
}
}
public void sleepResponsibly(int timeMillisecond){
try{
Thread.sleep(timeMillisecond);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
throw new RuntimeException(ex);
}
}
Hypthosis #2: The text nodes are complex. I have experienced a failure in method getText() to return text when the text nodes code complex formatting. I got around this by invoking the following instead:
public static String getTextFromElementsTextNodes(WebDriver webDriver, WebElement element) throws IllegalArgumentException {
String text = "";
if (webDriver instanceof JavascriptExecutor) {
text = (String)((JavascriptExecutor) webDriver).executeScript(
"var nodes = arguments[0].childNodes;" +
"var text = '';" +
"for (var i = 0; i < nodes.length; i++) {" +
" if (nodes[i].nodeType == Node.TEXT_NODE) {" +
" text += nodes[i].textContent;" +
" }" +
"}" +
"return text;"
, element);
} else {
throw new IllegalArgumentException("driver is not an instance of JavascriptExecutor");
}
return text;
}
A caveat is that getTextFromElementsTextNodes() may return non-ASCII charcters so I do the following:
System.out.println(getTextFromElementsTextNodes(wb,item).replaceAll("[^\\x00-\\x7F]", " "));
I could finally able to retrieve the options under the li. This is what I did and it worked
for(WebElement MyListOptions: listOfLiTags) {
String myoptions=serchOptions.getAttribute("<<The actual attribute value which is storing my options>>");
System.out.println("THE List Options are" + txt3);
}

How to put sql query result into an array -- Selenium Webdriver?

I'm trying to learn Selenium WebDriver and have a question that I cannot resolve long time. These are my first steps in Java and I appreciate your help.
I have a code that pools out the values from the DataBase table. This code should put that query result into an array and execute it repeatedly using every next row (For Loop), but I do not know how to do it. Currently it pools all rows, but runs only last row repeatedly (5 times). Could you please help me to create correct array with for loop? Tanks a lot in advance! Here is my code:
public class DB_TFETCHdata {
ProfilesIni listProfiles = new ProfilesIni();
FirefoxProfile profile = listProfiles.getProfile("selenium");
WebDriver oWD = new FirefoxDriver(profile);
String dbZipCode;
String dbDOBMonth;
String dbDOBDay;
String dbDOBYear;
int i = 0;
#Before
public void setUp() throws Exception{
oWD.get("https://www.ehealthinsurance.com/");
String ConnStr = "jdbc:sqlserver://localhost:1433;databaseName=TestData1; user=sa; password=1";
String DatabaseDriver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
String strSQL = "Select * FROM InfoTbl";
Class.forName(DatabaseDriver);
Connection conn = DriverManager.getConnection(ConnStr);
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(strSQL);
while(rs.next()){
dbZipCode = rs.getString("ZipCode");
dbDOBMonth = rs.getString("DOB_Month");
dbDOBDay = rs.getString("DOB_Day");
dbDOBYear = rs.getString("DOB_Year");
System.out.println(dbZipCode + "-" + dbDOBMonth + "-" + dbDOBDay + "-" + dbDOBYear);
//System.out.println("There were " + rowCount + " records.");
// rs.close();
//st.close();
//conn.close();
}
}
#Test
public void testLogin() throws Exception {
for (int i = 1; i<5; i++){
/*String strZipCode = oResultset [i][0];
String strDOBMonth = oResultset [i][1];
String strDOBDay = oResultset [i][2];
String strDOBYear = ArrXlDataLocal [i][3];*/
//new Select(oWD.findElement(By.name("insuranceType"))).selectByVisibleText("Dental");
//new Select(oWD.findElement(By.name("insuranceType"))).selectByVisibleText("Dental");
oWD.findElement(By.linkText("Dental")).click();
Thread.sleep(4000);
oWD.findElement(By.id("zipCode")).clear();
oWD.findElement(By.id("zipCode")).sendKeys(dbZipCode);
oWD.findElement(By.id("goBtn")).click();
oWD.findElement(By.id("census_primary_genderMALE")).click();
oWD.findElement(By.id("census_primary_month")).clear();
oWD.findElement(By.id("census_primary_month")).sendKeys(dbDOBMonth);
oWD.findElement(By.id("census_primary_day")).clear();
oWD.findElement(By.id("census_primary_day")).sendKeys(dbDOBDay);
oWD.findElement(By.id("census_primary_year")).clear();
oWD.findElement(By.id("census_primary_year")).sendKeys(dbDOBYear);
oWD.findElement(By.id("census_primary_tobacco")).click();
oWD.findElement(By.id("continue-btn")).click();
Thread.sleep(10000);
String strNumOfPlans = oWD.findElement(By.cssSelector("span.text-pink")).getText();
String strNumOfPlans2 = oWD.findElement(By.xpath("//*[#id='quote-title']/strong")).getText();
System.out.println("Here are the " + strNumOfPlans +" bestselling plans. Plans start at " + strNumOfPlans2);
}
}
#After
public void TearDown(){
}
}
You can use dataProvider feature of TestNG. Create a new function for dataProvider and do the database fetch steps inside this function, while reading each recordset, store the values in the object array. See below example code, did not test this code for errors.
#DataProvider
public Object[][] getData()
{
// open DB connection, get record set and store values in array object
//Rows - Number of times your test has to be repeated.
//Columns - Number of parameters in test data.
Object[][] data = new Object[3][2];
// you can dynamically read the rows/columns of recordset instead of hardcoding(new Object[3][2])
// 1st row
data[0][0] ="value1";
data[0][1] = "value2";
// similarly for all rows in the record set
return data;
}
#Test(DataProvider="getData")
public void testLogin(){
}

webdriver implicitWait not working as expected

In webdriver code if i use thread.sleep(20000). It's waiting for 20 seconds, and my code also works fine.
To archive the same if i use implicit wait like
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
It's not waiting forcefully for 20 seconds and goes to next steps just in 3 to 4 seconds. and page still loading.
This is wired situation as i am using fluent wait to find some elements. if the elements still loading on the page it does not show error and make the test passed.
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(50, TimeUnit.SECONDS)
.pollingEvery(5, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);
WebElement foo = wait.until(new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
return driver.findElement(By.id("jxxx"));
}
});
But if i say wrong id it waits for 50 seconds but other test got passed without clicking.. it is not showing any error.
My Question is how I should avoid Thread.sleep() as other selenium methods are not helping me..
Use below method to wait for a element:
public boolean waitForElementToBePresent(By by, int waitInMilliSeconds) throws Exception
{
int wait = waitInMilliSeconds;
int iterations = (wait/250);
long startmilliSec = System.currentTimeMillis();
for (int i = 0; i < iterations; i++)
{
if((System.currentTimeMillis()-startmilliSec)>wait)
return false;
List<WebElement> elements = driver.findElements(by);
if (elements != null && elements.size() > 0)
return true;
Thread.sleep(250);
}
return false;
}
And below method is to wait for page load:
public void waitForPageLoadingToComplete() throws Exception {
ExpectedCondition<Boolean> expectation = new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver driver) {
return ((JavascriptExecutor) driver).executeScript(
"return document.readyState").equals("complete");
}
};
Wait<WebDriver> wait = new WebDriverWait(driver, 30);
wait.until(expectation);
}
Let's assume you are waiting for a page to load. Then call the 1st method with waiting time and any element which appears after page loading then it will return true, other wise false. Use it like,
waitForElementToBePresent(By.id("Something"), 20000)
The above called function waits until it finds the given element within given duration.
Try any of below code after above method
WebDriverWait wait = new WebDriverWait(webDriver, timeoutInSeconds);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id<locator>));
or
wait.until(ExpectedConditions.elementToBeClickable(By.id<locator>));
Update:
public boolean waitForTextFiled(By by, int waitInMilliSeconds, WebDriver wdriver) throws Exception
{
WebDriver driver = wdriver;
int wait = waitInMilliSeconds;
int iterations = (wait/250);
long startmilliSec = System.currentTimeMillis();
for (int i = 0; i < iterations; i++)
{
if((System.currentTimeMillis()-startmilliSec)>wait)
return false;
driver.findElement(By.id("txt")).sendKeys("Something");
String name = driver.findElement(by).getAttribute("value");
if (name != null && !name.equals("")){
return true;
}
Thread.sleep(250);
}
return false;
}
This will try entering text in to the text field till given time in millis. If getAttribute() is not suitable in your case use getText(). If text is enetered then it returns true. Put maximum time that u can wait until.
You might want to try this for an element to become visible on the screen.
new WebDriverWait(10, driver).until(ExpectedConditions.visibilityOfElementLocated(By.id("jxxx")).
In this case, wait time is a maximum of 10 seconds.