if(driver.findElement(By.xpath("//div/h3[contains(text(),'MOVENPICK HOTEL DEIRA')]")).isDisplayed())
{
}
else if(driver.findElement(By.xpath("//div/h3[contains(text(),'HOTEL INN')]")).isDisplayed())
{
}
In the above code, if condition fails means how to execute else if(xpathcondition),
For failed condition its showing exception as "Element not Found". If I handled exception, how to execute else if??
Advance thanks for your help !!
Ideally isDisplayed() should return false instead of throwing exception.
You can go with saifur answer. Another approach would be (as per this)
try {
if(driver.findElement(By.xpath("//div/h3[contains(text(),'MOVENPICK HOTEL DEIRA')]")).isDisplayed())
{ }
}catch(){ //catch executes the else part when the exception is thrown.
if(driver.findElement(By.xpath("//div/h3[contains(text(),'HOTEL INN')]")).isDisplayed())
{ }
}
Check this issue as well
The issue here is if any of the elements look up fails the test will be terminated with NoSuchElement or Element not Found exception since element is not a part of the dom. To avoid this you can trick the code a little bit or do another check to see if the element exists first.
I would rather find the element and match the text instead and perform additional task
// Write a selector that would meet the find both elements
WebElement element = driver.findElement(By.cssSelector("div h3"));
if (element.getText().contains("MOVENPICK HOTEL DEIRA")) {
//do this
} else if (element.getText().contains("HOTEL INN")) {
//do something
} else {
//do nothing and log some error
}
Related
I have a loop, where I open links one by one. Inside this loop I have the if statement, which checks:
If I see name, then I copy it
If I don't see name, then I ignore it and continue looping.
List<WebElement> demovar = driver.findElements(By.xpath("//*[#id=\"big_icon_view\"]/ul/li/p/a"));
System.out.println(demovar.size());
ArrayList<String> hrefs = new ArrayList<String>();
for (WebElement var : demovar) {
System.out.println(var.getText());
System.out.println(var.getAttribute("href"));
hrefs.add(var.getAttribute("href"));
}
int i = 0;
for (String href : hrefs) {
driver.navigate().to(href);
System.out.println((++i) + ": navigated to URL with href: " + href);
if(driver.findElement(By.xpath("//a[#id='name']")).isDisplayed()) {
System.out.println("I can see Name");
} else {
System.out.println("I cant see Name");
}
Thread.sleep(3000); // To check if the navigation is happening properly.
}
Why is this not working properly? As I assume, it should have the following:
If the element is displayed then I can see Name
else the element is NOT displayed, then I cannot see Name.
I'm not sure what error message you are seeing here, but if your code is not working then it's quite likely the element is not displayed on the page, so you will receive an exception when attempting to locate it.
You can catch the NoSuchElementException to handle the case where the element does not appear on the page.
for (String href : hrefs) {
driver.navigate().to(href);
System.out.println((++i) + ": navigated to URL with href: " + href);
// create isDisplayed variable
boolean isDisplayed = true;
try {
isDisplayed = driver.findElement(By.xpath("//a[#id='name']")).isDisplayed();
}
catch(NoSuchElementException) {
isDisplayed = false;
}
// do something else here with isDisplayed
if (isDisplayed) { System.out.println("I can see Name"); }
else { System.out.println("I can not see Name"); }
}
This code does almost the same thing as yours, but we catch the NoSuchElementException that gets thrown if the element does not appear on the page.
If this does not work for you, feel free to post the error message or results you are seeing in your code, it'll help track down the issue.
API of the findElement(By by) in the Interface WebDriver states the following
"Find the first WebElement using the given method. This method is affected by the 'implicit wait' times in force at the time of execution. The findElement(..) invocation will return a matching row, or try again repeatedly until the configured timeout is reached. findElement should not be used to look for non-present elements, use findElements(By) and assert zero length response instead."
Which means that in case if the element is not found it keeps trying until configured timeout and throws the exception NoSuchElementException - If no matching elements are found
Hence it would be better to handle in the following ways
Using FindElements which returns a list of all WebElements, or an empty list if nothing matches as follows:
if(driver.findElements(By.ByXPath).size()<0)
Using a try/catch/finally to catch the NoSuchElementException and a boolean flag to determine if its present or not. The boolean flag can be set to false in case if exception is caught.
After #Christine help, i did a solution for me
for (String href : hrefs) {
driver.navigate().to(href);
boolean isPresent = driver.findElements(By.xpath("element")).size() > 0;
if (isPresent) {
String test = driver.findElement(By.xpath("element")).getText();
System.out.println(test);
} else {
System.out.println("Name not found");
}
Thread.sleep(3000); // To check if the navigation is happening properly.
}
}
}
And this is working fine =)
I am new to selenium.
I am trying to automate amazon login and log out.
I am facing couple of problems.
1.In login page the button "continue" appears after username when I try to login for first time.
But later when I try to login for second time , its does not appear.
How to handle this.
Here is the code I have written so far:
public void logindetails()
{
Datafile d=new Datafile("C:\\Users\\kirruPC\\selenium divers\\Data.xlsx",0);
String uname= d.username(0, 0);
WebElement u=driver.findElement(useid);
u.sendKeys(uname);
u.click();
if(driver.findElement(By.xpath(".//*[#id='continue']")).isDisplayed()==true)
{
driver.findElement(By.id("continue")).click();
String psw=d.pass(0,1);
driver.findElement(password).sendKeys(psw);
}
else
{
String psw=d.pass(0,1);
driver.findElement(password).sendKeys(psw);
}
}
Unable to locate sign Out element.
Below is the code I have written to move to sign out link and click:
public void logout() throws Exception
{
Actions a= new Actions(driver);
WebElement ele=driver.findElement(By.xpath(".//*[#id='nav-link-accountList']"));
a.moveToElement(ele).build().perform();
driver.findElement(By.xpath(".//*[#id='nav-al-your-account']"));
Thread.sleep(3000);
driver.findElement(By.xpath(".//*[#id='nav-al-your-account']/a[22]")).click();
}
Please help me
Thanks in advance
First of all, there is a high change that the element you are searching for might not exist at all in the page, so first let's check if the element exist (if the element does not exist, an exception is thrown, so let's add a handle for that as well). For all that, create a function like so:
public bool ElementExists(By locator)
{
try
{
driver.findElement(locator);
//If no exception is thrown here, element exists, so return true
return true;
}
catch (NoSuchElementException ex)
{
return false;
{
}
Now that we have a function that can safely check if an element exists without getting an exception, you can use it to determine if you will run the code handling the element.
Function isDisplayed() already returns a bool, so checking equality with true is not necessary.
if(ElementExists(By.xpath(...)).isDisplayed())
{
if(driver.findElement(By.xpath(".//*[#id='continue']")).isDisplayed())
{
driver.findElement(By.id("continue")).click();
}
}
//The code below will run either way, so move it out of the if statement
String psw=d.pass(0,1);
driver.findElement(password).sendKeys(psw);
As for the second part of your question, your code can be simplified by just, searching for the element and then clicking it like so:
driver.findElement(By.xpath(".//*[#id='nav-al-your-account']/a[22]")).click();
If you will, double-check the xpath or "catch" the element by an ID.
I am working on selenium and TestNG with java. I have some problem about how to handle the popup. In here, I have 2 process at a time. if I click on the button and it has an ingredient, then it will open a popup, otherwise it will add in a cart directly. So i used:
#Test
public void ingredient_Popup()
{
String ingre_Title="Choose product choices...";
String ingre_Title1=d.findElement(By.className("modal-dialog")).getText();
if(ingre_Title.contentEquals(ingre_Title1))
{
d.findElement(By.id("ingredient_quantity")).sendKeys("1");
d.findElement(By.linkText("SUBMIT")).click();
}
else
{
d.findElement(By.xpath("/html/body/section[3]/div[2]/div/div/div/div/div/div[1]/div[3]/div/div/div[3]/div/div[1]/table/tbody/tr/td[2]/div/span[2]/button")).click();
}
And also i used (II)
#Test
public void ingredient_Popup()WebElement element;
try
{
element = d.findElement(By.className("modal-dialog")); >}
catch(NoSuchElementException n)
{
element = null;
}
{
if(element !=null)
{
d.findElement(By.id("ingredient_quantity")).sendKeys("1");
d.findElement(By.linkText("SUBMIT")).click();
}
else
{
d.findElement(By.className("btn btn-default btn-number")).click();
}
}
And i used, isenabled, Contains, equals, isdisplayed, isElementPresent
if(ingre_Title.isEnabled())
{
d.findElement(By.id("ingredient_quantity")).sendKeys("1");
d.findElement(By.linkText("SUBMIT")).click();
}
else
{
d.findElement(By.xpath("/html/body/section[3]/div[2]/div/div/div/div/div/div[1]/div[3]/div/div/div[3]/div/div[1]/table/tbody/tr/td[2]/div/span[2]/button")).click();
}
And i tried a lot, Nothing is working. i'm getting NoSuchElementException
error.
So Kindly anyone make a code and share it with me.
Here the issue is to identify the scenario correctly. Just find the existence of the expected element in case of that particular scenario else otherwise.
For example, consider after clicking a button you might have two scenario's. Scenario A has element A and scenario B has element B then,
driver.findelement(By.xpath("button")).click;
//Identifying the scenario by checking the presence of the element
if(driver.findElements(By.xpath("A")).size>0)
{
//IF THIS IS TRUE NOW YOU ARE IN SCENARIO A
//DO YOUR STUFF ACCORDING TO SCENARIO A
}
else if(driver.findElements(By.xpath("B")).size>0)
{
//IF THIS IS TRUE NOW YOU ARE IN SCENARIO B
//DO YOUR STUFF INCASE OF SCENARIO B
}
Modify the logic as per your logic but the trick is in findelements. You can use this to check the presence of an element easily.
Hope this helps.
Thanks.
I would like to use conditional function using .isDisplayed() method. Everything is working correct as long as this method returns true.
HTML is not required I think here, because I have only one button to be visible on the page, which is correclty found (I successfully clicked the button with the following xpath.
Now I try with:
if (driver.findElement(By.xpath("//a[#id='button1']")).isDisplayed()) {
//do stuff
}
else {
//do other stuff
}
Or even
WebElement withdrawnBtn = driver.findElement(By.xpath("//a[#id='button1']"));
boolean isVisible = withdrawnBtn.isDisplayed();
if (isVisible) {
//do stuff
}
else {
//do other stuff
}
but both conditionals fails, if in the first run there should be executed code from else, because everytime when the button is not available, there is fail pointing on the line with driver.findElement(By.xpath("//a[#id='button1']")).isDisplayed()); - fails, because the button is not displayed. I need t o do something, when the button is not displayed instead failing code...
Before checking isDisplayed conditions we need to check whether element exist on the page or not Otherwise it will throw Nosuchelementfound exception
driver.findElements("Locator").size()-- will return integer value if the element exist on the page.
Below is the fix code.
int size = driver.findElements("Locator").size();
if(size!=0){
if(driver.findElement("Locator").isDisplayed()){
// do operations
}
}
After reading comments, I got to know isEmpty is better way to use instead of size I made changes to the above code.
WebDriver driver;
List<WebElement> webElements = driver.findElements(By.xpath("test"));
if(!webElements.isEmpty()){
if(driver.findElement(By.xpath("test")).isDisplayed()){
// do operations
}
}
Try it and let me know if it works for you
you can also use following to identify if an element exists or not:
private boolean isPresent(WebElement element) {
try {
element;
} catch (NoSuchElementException e) {
return false;
}
return true;
}
OK, I was thinking about catching NoElementFound exception, but I found this issue:
Selenium Webdriver: best practice to handle a NoSuchElementException
using link above I used:
List<WebElement> withdrawnBtn = driver.findElements(By.xpath("//a[#id='button1']"));
if (withdrawnBtn.size() != 0) {
//do stuff
}
else {
//do other stuff
}
Instead of size() method you could use isEmpty() method.
I wonder if someone could help me with an issue I'm having trying to work out and If statement in Java for Webdriver.
When logging into the app I am testing it is possible to be taken to a security questions page before the main page (if a new user etc). What I would like the code in my test to do is if presented with the security questions page fill it in and move on, if not check you are on the main page.
I was able to do this in Selenium RC using
if (selenium.isTextPresent("User Account Credentials Update")) {
selenium.type("//input[#id='securityQuestion']", "A");
selenium.type("//input[#id='securityAnswer']", "A");
selenium.type("//input[#id='emailAddress']", "test#test.com");
selenium.click("update");
selenium.waitForPageToLoad("30000");
}
assertTrue(selenium.isTextPresent("MainPage"));
Playing around with Webdriver I am using:
if(driver.findElement(By.id("securityQuestion")) != 0) {
driver.findElement(By.id("securityQuestion")).sendKeys("A");
driver.findElement(By.id("securityAnswer")).sendKeys("A");
driver.findElement(By.id("emailAddress")).sendKeys("test#test.com");
driver.findElement(By.id("update")).click();
Assert.assertTrue("Main Page is not Showing",
driver.getPageSource().contains("MainPage"));
The Problem with this is is that it always chucks an exception if the Security screen is not displayed. How do I need to set the code so that it ignores the security page stuff if that page is not presented?
Thank you for any help :-)
You can use driver.findElements as a way to check that a specific element is present without having exceptions thrown. This works because it will return a list of size 0 of WebElements if no element is found. At the moment, if Selenium tries to find an element using findElement and the element doesn't exist, it will throw a NoSuchElementException This means you can replace:
if (driver.findElement(By.id("securityQuestion")) != 0)
with this:
if (driver.findElements(By.id("securityQuestion")).size() != 0)
There is actually nothing wrong in an exception being thrown as long as you catch/handle it.
In other words, I'd follow the EAFP approach here:
try {
driver.findElement(By.id("securityQuestion"));
// ...
} catch (NoSuchElementException e) {
// handle exception, may be at least log in your case
}
I usually just wrap it into a method:
public boolean elementExists(By selector)
{
try
{
driver.findElement(selector)
return true;
}
catch(NoSuchElementException e)
{
return false;
}
}