if (wait.until(ExpectedConditions.elementToBeClickable(user.profileEdit)).isDisplayed()) {
wait.until(ExpectedConditions.elementToBeClickable(user.profileEdit)).click();
System.out.println("RECORD FOUND");
} else {
System.out.println("NO RECORD FOUND");
}
}
Thanks in advance!
wait.until(ExpectedConditions.elementToBeClickable(user.profileEdit)) - if element will not be clickable, TimeoutException will be thrown and .isDisplayed() will not be perform - you should choose wait or isDisplayed and rewrite your code accroding to it.
Element could be in frame if wait not work - you need just switch frame.
NoSuchElementException will be thrown in your case if user.profileEdit
element were initialized before it have been appeared - you can rewrite your test like this
test() {
element.click();
....
assertThat(driver.findElement(By.xpath("user.profileEdit")).isDisplayed())
.as("RECORD NOT FOUND");
}
Related
I use this code to click on
List<WebElement> list = driver.findElements(By.xpath("//div[#class='ag-center-cols-container']//div"));
// check for list elements and print all found elements
if(!list.isEmpty())
{
for (WebElement element : list)
{
// System.out.println("Found inner WebElement " + element.getText());
}
}
// iterate sub-elements
for ( WebElement element : list )
{
System.out.println("Searching for " + element.getText());
if(element.getText().equals(valueToSelect))
{
new WebDriverWait(driver, 30).until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("//div[#class='overlay ng-star-inserted']")));
element.click();
break; // We need to put break because the loop will continue and we will get exception
}
}
But from time to time I get this error at this line element.getText():
org.openqa.selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document
Do you know how I can implement a lister in order to fix this issue>
org.openqa.selenium.StaleElementReferenceException:
Indicates that a reference to an element is now "stale" --- the element no longer appears on the DOM of the page. The reason for this expectation is may be your DOM got updated or refreshed. For an example, after performing an action like click() your DOM may get updated or refreshed. In this time when you are trying to find an element on DOM you will experience this error.
You have to re-find that element in updated or refreshed DOM
But from time to time I get this error at this line element.getText():
Create a reusable method to handle this exception.
Code:
public static String getTextFromElement(WebElement element, WebDriver driver) {
try {
return element.getText();
} catch (org.openqa.selenium.StaleElementReferenceException e) {
new WebDriverWait(driver, 15).until(ExpectedConditions.visibilityOf(element));
return element.getText();
}
}
For example, you can call in this way.
System.out.println("Found inner WebElement " + getTextFromElement(element, driver));
The dropdown element is invisible but it is enable and present.
I have tried everything but I am out of options. Please help. My goal is to click that dropdown that will show a textfield to input a string.
Code snippet:
if(driver.findElements(By.xpath("//*[#id='s2id_autogen3']"))!= null){
System.out.println("Element is Present");
}else{
System.out.println("Element is Absent");
}
if( driver.findElement(By.xpath("//*[#id='s2id_autogen3']")).isDisplayed()){
System.out.println("Element is Visible");
}else{
System.out.println("Element is InVisible");
}
if( driver.findElement(By.xpath("//*[#id='s2id_autogen3']")).isEnabled()){
System.out.println("Element is Enable");
}else{
System.out.println("Element is Disabled");
}
Output:
Element is Present
Element is InVisible
Element is Enable
enter image description here
You can make Webdriver wait until the visibility of the required drop down and then click on it. Try following and let me know, whether it resolves your issue:
WebDriverWait wait = new WebDriverWait(driver, 60);
wait.until(
ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[#id='s2id_autogen3']")));
In the above code, Webdriver will wait for a maximum of 60 seconds for the required drop down to become visible. If even after 60 seconds the drop down is not visible, it will fail with a timeout error.
The answer by Mahipal has to work. Other reason might be the Frame. Make sure that dropdown is not inside an Frame.
I am trying to select date from the Datepicker.Following is the code
WebDriver d=new FirefoxDriver();
Actions a=new Actions(d);
String date="14";
d.get("http://www.eyecon.ro/bootstrap-datepicker/");
d.findElement(By.cssSelector("div#dp3>span")).click();
List<WebElement> trs=d.findElements(By.cssSelector("div.datepicker-days>table>tbody>tr"));
for(WebElement tr:trs) {
List<WebElement> tds=tr.findElements(By.tagName("td"));
for(WebElement td:tds) {
if(date.equals(td.getText())) {
a.moveToElement(td).click().build().perform();
}
}
}
With the above code i got stale element reference exception at this line of code
"if(date.equals(td.getText())) {"
so i have changed the code to this
for(WebElement td:tds) {
while(i<4) {
try {
if(date.equals(td.getText())) {
a.moveToElement(td).click().build().perform();
}
break;
}catch(Exception ex) {
}
System.out.println(i);
i++;
}
}
Now i am able to select the date.But the script is still throwing the stale element reference exception.The script is showing error at this line now
List<WebElement> tds=tr.findElements(By.tagName("td"));
I am working on this for the past 3 days.Any suggestions on how to solve this.
Thanks in advance
In your first code, after you clicked on the element, the DOM changed, as in the Date became "14", and since the both the for-loop were still iterating, hence it threw StaleElementReferenceException.
Similarly, in the second code, you did break the "inside for-loop" that was iterating the td elements, but you didn't break the "outside" one, that continued with iterating the tr elements, hence it threw StaleElementReferenceException yet again.
Resolution:- You should've come out of both the for-loops using break after the element was clicked, and hence averting the StaleElementReferenceException, in the process.
Below code shows how you could've broken out of both the for-loops without any exception:
WebDriver d=new FirefoxDriver();
d.manage().window().maximize(); //Maximizing window
d.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); //Implicit wait for 20 seconds
Actions a=new Actions(d);
String date="14";
int flag=0;
d.get("http://www.eyecon.ro/bootstrap-datepicker/");
d.findElement(By.cssSelector("div#dp3>span")).click();
List<WebElement> trs=d.findElements(By.cssSelector("div.datepicker-days>table>tbody>tr"));
for(WebElement tr:trs) {
List<WebElement> tds=tr.findElements(By.tagName("td"));
for(WebElement td:tds) {
if(date.equals(td.getText())) {
a.moveToElement(td).click().build().perform();
flag=1; // Set to 1 when the required element was found and clicked.
break; //To come out of the first for-loop
}
}
if(flag==1)
break; //Since the element was found, come out of the second for-loop.
}
NOTE:- I have added the code for maximizing windows and providing implicit wait too, which is actually advised when you are writing selenium scripts.
You should use WebDriverWait and ExpectedConditions to tackle staleness of an element. Below is modified block of your code which I tested and it works.
driver.findElement(By.cssSelector("div#dp3>span")).click();
WebDriverWait wait = new WebDriverWait(driver, 30);
List<WebElement> trs = wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.cssSelector("div.datepicker-days>table>tbody>tr")));
datePicker:
{
for (WebElement tr : trs) {
List<WebElement> tds = tr.findElements(By.tagName("td"));
for (WebElement td : tds) {
wait.until(ExpectedConditions.not(ExpectedConditions.stalenessOf(td)));
if (date.equals(td.getText())) {
td.click();
break datePicker;
}
}
}
}
For more information check WebDriverWait and ExpectedConditions here
Found an easier way to resolve my Stale Element Reference Exceptions.
In Java with Selenium2 try the code below:
public WebElement cleanAndRebuildElement(final WebElement ee) {
WebElement e2;
try {
e2=ee;
e2.isDisplayed();
logger.info("Element is cleaned : Not Stale Anymore !");
} catch (StaleElementReferenceException e) {
e2=null;
} catch(NoSuchElementException nse) {
nse.printstacktrace();
}
return e2;
}
}
As per my understanding when you perform element.click() in for loop DOM reloaded that's why it shows stale element exception.
Use following css selector[It will selected elements from expected date picker only, used this as there are multiple date pickers on page ] & apply break in for loop on matching date like below.It will select date 14 & breaks loop without exception -
String date="14";
d.get("http://www.eyecon.ro/bootstrap-datepicker/");
d.findElement(By.cssSelector("div#dp3>span")).click();
List<WebElement> trs=d.findElements(By.cssSelector(".datepicker.dropdown-menu:nth-of-type(4)>div.datepicker-days>table>tbody>tr>td"));
for(WebElement td:trs) {
if(date.equals(td.getText())) {
td.click();
break;
}
}
Issue:- webelement (Button) isdisplayed() doesn't works for negative scenarios
Requirement:- I need to fail a test flow in case a button is not displayed on the screen and if its present, then proceed with the flow
Code:-
if (driver.findElement(By.id("button")).isDisplayed() == false) {
System.out.println("The Button isn't present. Exiting!!");
driver.findElement(By.linkText("Logout")).click();
}
else
{
//Proceed with the positive flow
}
In above code, if the button is not present at all on the screen, the test should fail (if statement should be executed, but it's not)
As TestAutomationEngr has mentioned, make sure there is only one type of such button on the page...
one more way you could test for negative flow in webdriver is by using a try and catch..
In your case,
boolean buttonFound=false;
try
{
new WebDriverWait(driver,10).until(ExpectedConditions.visibilityOfElementLocated(By.id("button")));
buttonFound=true;
}catch(Exception e)
{
System.out.println("The Button isn't present. Exiting!!");
driver.findElement(By.linkText("Logout")).click();
}
if(buttonFound)
{
//positive flow
}
here it'l wait for 10 secs for visibility of element,
if found, buttonFound is set to true,hence positive flow is executed
if not found, the message in catch clause will be displayed and logout link will be clicked
In fact it is not required to logout in case an exception is thrown because when the driver is closed this session will be lost. The following code will fail the test in case the element is not present or it is not enabled.
WebElement elem = driver.findElement(By.id("button"));
Assert.assertTrue(elem.isEnabled());
At the end you just need to close the driver in the test teardown the
driver.close()
You can use the FindElements.Count approach.
Like this:
public bool IsElementDisplayed(IWebDriver driver, By element)
{
if (driver.FindElements(element).Count > 0)
{
if (driver.FindElement(element).Displayed)
return true;
else
return false;
}
else
{
return false;
}
}
Hope it helps.
I'm trying to handle dialog (Ok Cancel type) with selenium WebDriver. So my aim is to click "Ok" button.
Scenario is:
Click button for invoking dialog
button.click();
Try to accept
webDriver.switchTo().alert().accept();
But I'm always getting NoAlertPresentException and seeing that dialog closes almost immediately.
It seems to me that Selenium automatically closes dialog and when I want to accept, there is nothing to accept.
I'm sorry for my bad English.
The usual cause of this issue is that Selenium is too quick and tries to accept an alert that has not yet been opened by the browser. This can be simply fixed by an explicit wait:
button.click();
WebDriverWait wait = new WebDriverWait(driver, 5);
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
alert.accept();
Step 1:
public boolean isAlertPresent(){
boolean foundAlert = false;
WebDriverWait wait = new WebDriverWait(driver, 0 /*timeout in seconds*/);
try {
wait.until(ExpectedConditions.alertIsPresent());
foundAlert = true;
System.out.println("isAlertPresent : " +foundAlert);
} catch (TimeoutException eTO) {
foundAlert = false;
System.out.println("isAlertPresent : " +foundAlert);
}
return foundAlert;
}
Step 2:
public boolean tocheck_POP_Dialog()
{ Alert alert;
try
{
alert=driver.switchTo().alert();
}
catch(NoSuchElementException elementException)
{
return false;
}
alert.accept(); //Close Alert popup
return true;
}
Step 3 :
if(dummyPage.isAlertPresent())
{
dummyPage.tocheck_POP_Dialog();
}
public boolean isAlertPresent(){
try{
Alert a = new WebDriverWait(driver, 10).until(ExpectedConditions.alertIsPresent());
if(a!=null){
System.out.println("Alert is present");
driver.switchTo().alert().accept();
return true;
}else{
throw new Throwable();
}
}
catch (Throwable e) {
System.err.println("Alert isn't present!!");
return false;
}
}
Use explicit wait to check the alert and then do the operation. This might help you. :)
Generally it happens because Selenium commands run too quick and it tries to close the alert before it is open. Hence, adding a delay after click event should resolve the issue. Also, if you are using Safari browser for your test, there is some issue with SafariDriver in handling alerts. SafariDriver cannot handle alerts should provide you more details.
Some additional info. for future readers of this thread:
If this exception persists even after the wait aspect is addressed, please check if the following sequence of steps is effective in the test script:
the underlying Html page's DOM is queried/parsed for some purpose (e.g. to look for Form errors)
(before the) driver.switch_to.alert is attempted
When an Alert is shown over an Html page, if the Alert is overlooked and the DOM underlying the Html page is queried first, the Webdriver appears to loose track of the Alert & causes the Exception.
This was observed with: geckodriver 0.21.0, Firefox 66.0b10 (64-bit) ; python 3.6.1 Selenium driver 3.14 (for Python).
Performing (2) before (1) was found to resolve the issue.