Selenium Webdriver Element not exists condition fails - java

I have a If Else block within a while block. If element is present, click it to remove it and put it back to parent list. Else if element is not in the list then select from parent list and put it back.
The first time it works. It sees that the element is present, clicks it to removes it. On the second pass it fails when checking for the element
I tried with FindElement.IsDisplayed and !=null.
I get this exception :
org.openqa.selenium.NoSuchElementException: Unable to find element with css selector == select[id="idSelSelectedLanes"]>option[value="9012"] (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 30.16 seconds
What am I missing?
This is my first post here so apologize for any formatting issues.
thanks
count ++;
if(count % 2 == 0){
if(BROWSER.equals("IE")) {
// check if 9012 is present
if(driver.findElement(By.cssSelector("select[id=\"idSelSelectedLanes\"]>option[value=\"9012\"]"))!=null){
try {
// since its present, click to remove
driver.findElement(By.cssSelector("select[id=\"idSelSelectedLanes\"]>option[value=\"9012\"]")).click();;
Thread.sleep(1000);
} catch(NoSuchElementException e) {
System.out.println("Couldn't remove 9012");
}
} else {
try {
//Not present, so select from Available Lanes
driver.findElement(By.cssSelector("select[id=\"idSelAvailableLanes\"]>option[value=\"9012\"]")).isDisplayed();
} catch (NoSuchElementException e) {
System.out.println("Couldn't add 9012");
}
}
}
}

You need to put driver.findElement(...) in a try-catch block
count ++;
WebElement e;
if(count % 2 == 0) {
if(BROWSER.equals("IE")) {
// check if 9012 is present
try {
e = driver.findElement(By.cssSelector("select[id=\"idSelSelectedLanes\"]>option[value=\"9012\"]"));
Thread.sleep(1000);
e.click()
} catch (NoSuchElementException e) {
System.out.println("Couldn't remove 9012");
// the else part goes here
}
}
}
Another approach is to use findElements instead of findElement to avoid the try-catch, and use .get(0) to get the element you want.

Another solution, you should check elementExist first using findElements, if it exists -> perform other actions
count ++;
WebElement e;
String e9012Css = "select[id=\"idSelSelectedLanes\"]>option[value=\"9012\"]";
if(count % 2 == 0) {
if(BROWSER.equals("IE")) {
// check if 9012 is present
e9012Existed = driver.findElements(By.cssSelector(e9012Css)).size() > 0;
if(e9012Existed) {
driver.findElement(By.cssSelector(e9012Css)).Click();
}
}
else {
System.out.println("Couldn't remove 9012");
}
}

try to use isElementPresent
if(isElementPresent(By.cssSelector("select[id=\"idSelSelectedLanes\"]>option[value=\"9012\"]"))){
// since its present, click to remove
} else {
//Not present, so select from Available Lanes
}

Related

if else?? try?? I need help on methods

If one method work and other doesn't then how do I make the code try a alternative method?
Here is the code
1st method
driver.findElement(By.id("com.simplemobiletools.gallery:id/dir_thumbnail")).click();
driver.findElement(By.id("com.simplemobiletools.gallery:id/medium_thumbnail")).click();
2nd method
driver.findElement(By.id("com.offerup:id/circle")).click();
driver.findElement(By.id("com.offerup:id/done")).click();
If the first method doesn't work I want it to go ahead and try the second method but, I don't know what command to use for this.
I am not very experienced at programming so please bear with me.
You can use try catch block for this purpose :
try {
driver.findElement(By.id("com.simplemobiletools.gallery:id/dir_thumbnail")).click();
driver.findElement(By.id("com.simplemobiletools.gallery:id/medium_thumbnail")).click();
catch (Exception e) {
driver.findElement(By.id("com.offerup:id/circle")).click();
driver.findElement(By.id("com.offerup:id/done")).click();
}
you can give a specific exception too, for example "ElementNotFoundException" or "ElementNotVisibleException" in your catch parameter type
I assume by "doesn't work" you mean the element wasn't found. Two options:
According to the documentation, findElement raises a NoSuchElementException if the element isn't found. So you can continue to use findElement and catch the exception via try/catch.
Alternately, use findElements, which returns a List, and branch based on whether any were found. As LuisGP pointed out, avoiding exceptions is often helpful.
Option 1:
try {
driver.findElement(By.id("com.simplemobiletools.gallery:id/dir_thumbnail")).click();
driver.findElement(By.id("com.simplemobiletools.gallery:id/medium_thumbnail")).click();
} catch (NoSuchElementException e) {
driver.findElement(By.id("com.offerup:id/circle")).click();
driver.findElement(By.id("com.offerup:id/done")).click();
}
Or if you meant to handle those one-by-one:
try {
driver.findElement(By.id("com.simplemobiletools.gallery:id/dir_thumbnail")).click();
} catch (NoSuchElementException e) {
driver.findElement(By.id("com.offerup:id/circle")).click();
}
try {
driver.findElement(By.id("com.simplemobiletools.gallery:id/medium_thumbnail")).click();
} catch (NoSuchElementException e) {
driver.findElement(By.id("com.offerup:id/done")).click();
}
Option 2 (if you want to handle them one-by-one, you should be able to tweak if you want to branch on just the first result):
List<WebElement> elements;
elements = driver.findElements(By.id("com.simplemobiletools.gallery:id/dir_thumbnail"));
if (element.size() == 0) {
driver.findElement(By.id("com.offerup:id/circle")).click();
} else {
elements.get(0).click();
}
elements = driver.findElements(By.id("com.simplemobiletools.gallery:id/medium_thumbnail"));
if (elements.size() == 0) {
driver.findElement(By.id("com.offerup:id/done")).click();
} else {
elements.get(0).click();
}
You can try click on an element out of 4 given elements which is visible and clickable. It will make you to safe to clicking on element after catching exception and good practice to follow. It will throw exception only when no element will be found out of 4 and it is valid case.
MobileElement A = driver.findElement(By.id("com.simplemobiletools.gallery:id/dir_thumbnail"));
MobileElement B = driver.findElement(By.id("com.simplemobiletools.gallery:id/medium_thumbnail"));
MobileElement C = driver.findElement(By.id("com.offerup:id/circle"));
MobileElement D = driver.findElement(By.id("com.offerup:id/done"));
public void clickOnElement() {
try {
if(A.isDisplayed() && A.isEnabled())
{
A.click();
}
if(B.isDisplayed() && B.isEnabled())
{
B.click();
}
if(C.isDisplayed() && C.isEnabled())
{
C.click();
}
if(D.isDisplayed() && D.isEnabled())
{
D.click();
}
}catch (Exception e) {
e.printStackTrace();
}
}
Just call 'clickOnElement' method in your test case.

POP function for Present&enabled checking in selenium (Java)

I working in selenium and now for checking visibility of element i use following wait until:
#FindBy (css=".delete-basket-modal-btn") WebElement deleteItemFromBasketCancelButton;
public void clickDeleteItemFromBasketCancelButton() throws InterruptedException {
wait.until(ExpectedConditions.elementToBeClickable(deleteItemFromBasketCancelButton));
deleteItemFromBasketCancelButton.click();
}
that's not good idea, this function is not checking for presence of element, so sometimes i get 'stale element reference element is not attached to the page document'
Now i trying to create universal function which will be inherited by all of mine page object class. In this function i need checking (5 sec) for presence, enability, clickability and visibilty of WebElement passed in argument.
For this moment i have new function below, but i dont know that is good approach for my problem
public void verifyElement(WebElement element) throws InterruptedException {
boolean isPresent = false;
for (int i = 0; i < 5; i++) {
try {
if (element != null) {
isPresent = true; // metoda do czekania na element
break;
}
} catch (Exception e) {
// System.out.println(e.getLocalizedMessage());
Thread.sleep(1000);
}
}
Assert.assertTrue(isPresent, "\"" + element + "\" is not present.");
boolean isEnabled = false;
for (int i = 0; i < 5; i++) {
try {
if (element.isEnabled()==true) {
isEnabled = true;
break;
}
}catch (Exception e) {
Thread.sleep(1000);
}
}
Assert.assertTrue(isEnabled, "\"" + element + "\" is not enabled.");
}
Do you have any suggestion or similar problem for this issue?
StaleElementReferenceException doesn't (necessarily) mean the element is not present, it means the DOM had changed/refreshed since the element was located, so the element reference which the driver holds is no longer valid. This is a disadvantage of using PageFactory model.
The solution is to locate the element just before the click operation, however this will break the consistency of the page object. Instead of using FindBy send By to the method and locate the element there
public void clickDeleteItemFromBasketCancelButton(By by) throws InterruptedException {
WebElement deleteItemFromBasketCancelButton = wait.until(ExpectedConditions.elementToBeClickable(by));
deleteItemFromBasketCancelButton.click();
}
The first written code is enough. To overcome stale element exception write code in try/catch block and use ExpectedConditions.stalenessOf(deleteItemFromBasketCancelButton) for presence, enability, clickability and visibilty (for any type of operation).
Try below one, hope it's help for you.
try{
wait.until(ExpectedConditions.elementToBeClickable(deleteItemFromBasketCancelButton));
deleteItemFromBasketCancelButton.click();
}
catch(Exception e){
wait.until(ExpectedConditions.refreshed(ExpectedConditions.stalenessOf(deleteItemFromBasketCancelButton)))
deleteItemFromBasketCancelButton.click();
}

Unable to perform click on the "PrestaShop" link in an IFrame like picture shown below

Am having an issue where I need to perform a click using Selenium Java on the link "PrestaShop" shown below. It's in an IFrame and my code is also below the picture.
Link to be clicked
When inspect the link using FireBug, it shows like below
Inspect using FireBug
And below is my code
try {
List<WebElement> frames = getAllFrames();
for (int i = 0; i < frames.size(); i++) {
WebElement frame = frames.get(i);
driver.switchTo().frame(frame);
if (driver.findElement(By.xpath(".//*[#classname='_1drp _5lv6']/a")).getSize() != null) {
driver.findElement(By.className(".//*[#classname='_1drp _5lv6']/a")).click();
} else {
driver.switchTo().defaultContent();
}
}
} catch (NoSuchElementException ex) {
System.out.println(ex.getMessage());
}
The code is getting all frames on the page and verify if the link "PrestaShop" is presence on the frame. If yes then it needs to fire a click on the link. Now, instead it returns error message - Unable to locate element: .//*[#classname='_1drp _5lv6']/a
Can please help to advise how can I fire the click successfully on the link?
While checking the presence of element, try using findElements instead of findElement. Below code might give you some idea.
List<WebElement> frames = getAllFrames();
for (int i = 0; i < frames.size(); i++) {
WebElement frame = frames.get(i);
driver.switchTo().frame(frame);
//use driver.findElements
if (driver.findElements(By.xpath(".//*[#classname='_1drp _5lv6']/a")).getSize() != null) {
driver.findElement(By.xpath("//*[contains(text(),'PrestaShop')]")).click();
} else {
driver.switchTo().defaultContent();
}
}
} catch (NoSuchElementException ex) {
System.out.println(ex.getMessage());
}
Hope this helps you. Thanks.
You can use following updated code:
List<WebElement> frames = getAllFrames();
for (int i = 0; i < frames.size(); i++) {
WebElement frame = frames.get(i);
driver.switchTo().frame(frame);
if (driver.findElement(By.xpath("//*[contains(text(),'PrestaShop')]")).getSize() != null) {
driver.findElement(By.xpath("//*[contains(text(),'PrestaShop')]")).click();
} else {
driver.switchTo().defaultContent();
}
}
} catch (NoSuchElementException ex) {
System.out.println(ex.getMessage());
}
Hope it will work for you.
thanks for your comment. I realized its because of the FB link was loaded too slow and hence the code fails. It's able to click now with below code if I added a Thread.sleep(30000) there.
if (driver.findElements(By.xpath(".//*[#class='lfloat']/div/a")).size() > 0) {
System.out.println("Found elements.");
driver.findElement(By.xpath("//*[contains(text(),'PrestaShop')]")).click();
} else {
System.out.println("Element not found.");
driver.switchTo().defaultContent();
}
However, if I want a FluentWait, then below code will just stop if the condition was not met
if (wait.ignoring(StaleElementReferenceException.class).ignoring(TimeoutException.class)
.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(".//*[#class='lfloat']/div/a")))
.isDisplayed()) {
System.out.println("Found elements.");
driver.findElement(By.xpath("//*[contains(text(),'PrestaShop')]")).click();
} else {
System.out.println("Element not found.");
driver.switchTo().defaultContent();
}
It just return message Expected condition failed: waiting for visibility of element located by By.xpath: .//*[#class='lfloat']/div/a (tried for 30 second(s) with 500 MILLISECONDS interval) and then not continue the loop. Can I know what's the way to make the code to continue even if the condition was not met?

Appium can not find any element

I'm have on automation project(java, appium, android)
In this project, the elements are stored in the database.
I get elements from database and try to find it:
1) Locator search using findElements:
if (!elementPath.equals("")){
List elementFound = driverCommands.findElements(By.xpath(elementPath));
if (elementFound.size() == 0){
return null;
}
return (AndroidElement) elementFound.get(0);
}
2) Locator search using findElement:
String elementPath = entity.getElementPath();
driverCommands.findElement(By.xpath(elementPath));
In both cases I get nothing. But if I add sleep() before usage findElemen(s) with a wait of at least 4 seconds, as shown in the example below, then the element will be found.
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (!elementPath.equals("")){
List elementFound = driverCommands.findElements(By.xpath((elementPath));
if (elementFound.size() == 0){
return null;
}
return (AndroidElement) elementFound.get(0);
How can I solve this problem?

Selenium - Java Wait for page to load fails in test scripts

I create test cases in Eclipse IDE using JAVA with some Selenium scripts.
My Problem is that sometimes, Continuous Run of Test Cases produce error/failed test in the selenium.waitForPageToLoad("30000") method. I made a solution that the method will loop until a specific condition is met so I came to this code. BUT THIS DOESN'T WORK.
This what happens: Run Junit Test > #Test1,2,3..n > page does not load # Test n > execute next line code > failed test in #Test n > because Page does not load so the next scripts cannot be done (missing required elements in the page because it doesn't load).
This what SUPPOSED to happen:Run Junit Test > #Test1,2,3..n > page does not load # Test n > wait for page to load until Specific condition is met (ex. Element X is already present in the page)> execute next line code > passed test in #Test n
I need a Solution that wait the Page to load until the element required for the next lines of scripts is present.
THIS CODE DOESN'T WORK. I badly need your help. Thanks
//Wait for Page to Load until Expected Element is not Present
public void waitForPageToLoadElement(final String isElementPresent){
boolean elementBoolean;
do{
selenium.waitForPageToLoad("30000");
elementBoolean = selenium.isElementPresent(isElementPresent);
if (elementBoolean==false){
try{Thread.sleep(3000);}
catch (Exception e) {
//catch
}}
}
while(elementBoolean==false);
}
//Wait for Page to Load until Expected Text is not Present
public void waitForPageToLoadText(String isTextPresent){
boolean elementBoolean;
do{
selenium.waitForPageToLoad("30000");
elementBoolean = selenium.isTextPresent(isTextPresent);
if (elementBoolean==false){
try{Thread.sleep(3000);}
catch (Exception e) {
//catch
}}
}
while(elementBoolean==false);
}
//Opens url until Expected Element is not Present
public void openUrl(String url){
boolean userNameBoolean, passwordBoolean;
do {
selenium.open(url);
userNameBoolean = selenium.isElementPresent("id=loginForm:username");
passwordBoolean = selenium.isElementPresent("id=loginForm:password");
if (userNameBoolean==false && passwordBoolean==false){
try{Thread.sleep(3000);}
catch (Exception e) {
//catch
}}
}while (userNameBoolean==false && passwordBoolean==false);
}
This type of logic might be helpful for you
public static void waitforElement(Selenium selenium,String element)
{
try
{
int second;
for (second = 0; ; second++)
{
if (selenium.isElementPresent(element))
{
break;
}
if (second >= 20)
{
break;
}
Thread.sleep(1000);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
Before doing any operation with any element just call this method for that element so that it will wait for that element until timeout reached (i.e., 20sec) if that element is not found.
Example
waitforElement(selenium,"id=loginForm:username");
selenium.type("id=loginForm:username","username");
waitforElement(selenium,"id=loginForm:password");
selenium.type("id=loginForm:password","password");
selenium.click("submit");

Categories

Resources