Selenium finding element - java

I'm trying to find the element but I'm getting an error
This is my code:
driver.get(baseURL);
driver.manage().timeouts().implicitlyWait(10 ,TimeUnit.SECONDS);
driver.manage().window().maximize();
//String parentHandle=driver.getWindowHandle();
driver.findElement(By.linkText("Create Account")).click();
System.out.println(driver.getCurrentUrl());
//String currentWindow=driver.getWindowHandle();
//driver.switchTo().window(currentWindow);
//String currentURL=;
//(currentURL);
for (String winHandle : driver.getWindowHandles()) {
driver.switchTo().window(winHandle); // switch focus of WebDriver to the next found window handle (that's your newly opened window)
}
driver.findElement(By.xpath("//html/body/div/div[1]/div[1]/div/div/form/div[1]/input")).sendKeys("9051902811");
driver.close();
//driver.switchTo().window(parentHandle);
}
catch(NoSuchElementException nsee){
System.out.println(nsee.toString());
}
System.exit(0);
}
And I am getting the exception:
Unable to locate element "method":"xpath","selector":"//html/body/div/div[1]/div[1]/div/div/form/div[1]/input"} Command duration or timeout: 89 milliseconds
please help...

Based on what you have shown it is hard to say exactly what the issue is. It could be a couple different things.
1) Does the element exist? If you show the html this could be answered very quickly.
Xpaths are very brittle and very much error prone.
Try to use a different selector if at all possible, id and class are much more reliable.
Here is the link to the By class.
driver.findElement(By.id("id")).sendKeys("keys");
driver.findElement(By.className("className")).sendKeys("keys");
Something that is more concrete, and when content is added that changes the structure, it doesn't break the tests, xpaths wil certainly make your tests brittle.
2) Is the input box loaded yet?
Selenium sometimes will try to find an element that isn't loaded yet. Explicit Waits will help solve this issue, you can use these waits along with ExpectedConditions to wait for an element to be visible, clickable, not visible, among other things. Do Not use thread.sleep unless there is no other choice(which there probably is).
The below code can be used to wait for the element to be visible.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
WebDriverWait wait = new WebDriverWait(driver, seconds);
wait.until(ExpectedConditions.visibilityOfElementLocated(By
.xpath(xpath)));
You can use this to ensure the element is visible by xpath, but if possible you should consider using a different selector, one that won't make your test very visible. If the element does not have an id/class, you can anchor the xpath to a more reliable selector as well, to reduce some brittleness.
I will be happy to provide more info, if you provide the html.

Related

xpath tested and correct but i recieve the error : no such element: Unable to locate element

My Xpath is correct & no iFrame and I can locate element in Chrome console but my program still fails. I have used explicit wait also.
no such element: Unable to locate element: {"method":"xpath","selector":"//*[contains(#ng-click,'authenticationCtrl.onSubmitMage()')]"}
i tested my xpath with Try xpath and it works but when i compile my code i still recieve the error
the page Object :
package com.orange.pageObject;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.CacheLookup;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class MageReferentiel {
WebDriver webdriver;
public MageReferentiel(WebDriver rwebDriver) {
webdriver = rwebDriver;
PageFactory.initElements(webdriver, this);
}
#FindBy(xpath = "//*[contains(#ng-click,'authenticationCtrl.onSubmitMage()')]")
#CacheLookup
WebElement connexion;
public void clickConnexion() {
connexion.click();
}
The step definition :
#When("l utilisateur choisi le referentiel")
public void l_utilisateur_choisi_le_referentiel() throws Exception {
mr.clickConnexion();
Thread.sleep(3000);
}
im looking to click in button
thanks
I agree with #Prophet, it could be because of some JS call the button, //*[contains(#ng-click,'authenticationCtrl.onSubmitMage()')] changing it's state to some other state. so what we can do about is that, to try with different locator.
such as :
//button[#translate ='LOGIN']
and see if that works, even if it doesn't try changing it to css.
Since ng elements are going very well with Protractor (Angular), better to use in Protractor in that case, so it suppose to be something like element(by.click('authenticationCtrl.onSubmitMage').click();
I guess the ng-click attribute value is dynamically updated on the page, so when you trying to access that element this element is changed, not having it's initial state.
Instead of locator you are using try this XPath:
//button[contains(text(),'Connexion')]
or this
//button[#translate='LOGIN']
The second element with this locator will be
(//button[#translate='LOGIN'])[2]
Looks like the element is not rendering on time. Try using explicit wait. Following gif shows how it is done using Cucumber:
https://nocodebdd.live/waitime-cucumber
Same been implemented using NoCodeBDD:
https://nocodebdd.live/waittime-nocodebdd
Disclaimer: I am the founder of NoCodeBDD so BDD automation can be achieved in minutes and without code. Through NoCodeBDD you could automate majority of the scenarios and it allows you to write your own code if there are edge cases. Would love to get some feedback on the product from the community. Basic version (https://www.nocodebdd.com/download) is free to use.
The default wait strategy in selenium is just that the page is loaded.
You've got an angular page so after your page is loaded there is a short delay while the JS runs and the element is finally ready in the DOM - this delay is causing your script to fail.
Check out the selenium docs here for wait strategies .
Your options are:
An explicit wait - This needs to be set per element you need to sync on.
I note you say you've used an explicit wait - but where? - It's not present in the code you shared and it might be that you've used the wrong expected condition.
Try something like this:
WebElement button = new WebDriverWait(rwebDriver, Duration.ofSeconds(10))
.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[contains(#ng-click,'authenticationCtrl.onSubmitMage()')]")));
button.click();
Use an implicit wait - you only use this once when you initialise driver and it will wait the specified amount of time for all element interaction.
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
There are other reasons that selenium returns a NoSuchElement but synchronisation is the most common one. Give the wait a go and let me know if it is still giving you trouble.
Through discussion in the comments, the trouble is an iframe
If you google it - there are lots of answers out there.
With frames, you need to identify it, switch to it, do your action(s) then switch back:
//find and switch - update the By.
driver.switchTo().frame(driver.findElement(By.id("your frame id")));
//actions go here
//back to normal
driver.switchTo().defaultContent();

I find the Register button using xpath but it's showing 2 matching nodes . How to uniquely identify the register button

Snap of the DOM here two matching nodes displayed for XPATH :
.//*[#id='header']/div/div[2]/div/a[2]
You can try this xpath - //div[#id='header'][not(#class)]//div[#class='right-side']/div/a[contains(.,'Register')]
There are two almost same div containers. Only difference is that the relevant container does not have a class attribute, so the not part.
Or you can use xpath with index - (//div[#class='right-side']/div/a[contains(.,'Register')])[1]
No need to find unique identifier for this, you can use find elements and click by index.
driver.findElements(By.xpath("//*[#id='header']/div/div[2]/div/a[2]")).get(index).click();
OR
You can use CSS Selector and locate the relevant element by using :nth-child(index).
In your case:
driver.findElement(By.cssSelector("#header:nth-child(index) a.button.border:nth-child(1)")).click();
There are more different ways to locate the element using css selectors and I suggest to read about.
And when you inspect the element using the browser you can choose copy css or xpath, this option will give you the unique locator.
A quick and dirty solution (//[#id='header']/div/div[2]/div/a[2])[1] for the first one or (//[#id='header']/div/div[2]/div/a[2])[2] for the second one. But really you should practice writing more relative xpaths and not just taking what the plugins give you.
Don't go for the complicated xpaths
This would work fine: By.xpath("(//A[#href='/Account/Register'])[1]")
I hope the below code helps you.
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Upmile {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("http://upamile.com");
//This website shows a dialog box at first
//we can skip that dialog by clicking on the body
driver.findElement(By.tagName("body")).click();
Thread.sleep(2000);
driver.findElement(By.xpath("(//A[#href='/Account/Register'])[1]")).click();
System.out.println("Test ran successfully");
}
}

Bug in Implicit Waits() in Selenium WebDriver

i'm stuck in a funny situation.
Whenever I use implicit wait in my code, my driver is able to locate the elements via its XPath. However when I comment out the implicit wait command, then is not able to locate the element.
Then I was doing some research, and later when I executed the code, I got a different kind of bug. It said "unknown error: cannot get automation extension".
This is really funny because, the wait commands are impacting the way the WebDriver is looking for element on the page.
Please suggest why this is happening and do share your experience if it has happened to any of you before.
The code that is throwing the error is below:-
package xyz;
//import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Asnmnt11
{
public static void main(String[] args) //throws InterruptedException
{
System.setProperty("webdriver.chrome.driver", "C:\\Users\\Vardhan\\workspace\\SeleniumProject\\files\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://facebook.com");
//driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElement(By.cssSelector("input.inputtext")).sendKeys("user#gmail.com");
driver.findElement(By.cssSelector("input[tabindex='2']")).sendKeys("password");
//Thread.sleep(2000);
driver.findElement(By.xpath(".//*[#id='u_0_2']")).click();
//driver.manage().timeouts().implicitlyWait(5000, TimeUnit.SECONDS);
driver.quit();
}
}
Thanks in advance.
When you remove implicit wait then the driver doesn't know how long it should look for the element. It does a quick search and if the element is not present then it will throw the element not found exception.
Xpath elements take more time to find. So it is always good to have an implicit wait. Why?
Searching elements can take time
Website is still loading
Elements are still loading
When I ran your test without any implicit wait the driver gave up finding the element quite fast.
org.openqa.selenium.NoSuchElementException:
no such element: Unable to locate element: {"method":"xpath","selector":".//*[#id='u_0_2']"}
Command duration or timeout: 0 milliseconds
This indicates that the driver was looking for the element for 0 milliseconds and it didn't find it. So it is always a good idea to have an implicit wait.
unknown error: cannot get automation extension
This issue is mostly an chromedriver and chrome issue. Usually is caused by using an older chromedriver version that is not compatible with your current chrome version. Chrome is automatically updated so try to update your chromedriver as well.
If you search element by xpath then it take more time to locate so that it is better to use Implicit or explicit wait. When I used your code without wait some time it throw NoSuchElementException.
AS facebook page take littile time to load and you are trying xpath to locate the elements so it is well and good to use Implicit or explicit wait.
Now as you got the issue
unknown error: cannot get automation extension
it is chromedriver issue, sometime I also got it when i used ChromeOptions. So It is totally irrelevant issue relate with Implicit wait

Cannot pick a random search result using Selenium with java

As a novice to selenium, I am trying to automate a shopping site on selenium webdriver with java, My scenario is that when i search with a keyword and get results, i should be able to pick any one of the results randomly, but I am unable to pick the random search result, either I am getting a "No such element" or when i try to click the same result everytime,search results seem to vary from time to time. please help on how to proceed further.
here is the code :
package newPackage;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.FluentWait;
import org.openqa.selenium.support.ui.Wait;
public class flipKart {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver","C:\\chromedriver.exe");
WebDriver dr = new ChromeDriver();
dr.get("http://m.barnesandnoble.com/");
dr.manage().window().maximize();
dr.findElement(By.xpath(".//*[#id='search_icon']")).click();
dr.findElement(By.xpath(".//*
[#id='sk_mobContentSearchInput']")).sendKeys("Golden Book");
dr.findElement(By.xpath(".//*
[#id='sk_mobContentSearchInput']")).sendKeys(Keys.ENTER);
dr.findElement(By.xpath(".//[#id='skMob_productDetails_prd9780735217034']/div/div")).click();
dr.findElement(By.xpath(".//*[#id='pdpAddtoBagBtn']")).click();
}
}
You should write any method that would try to wait for the visibility of the element that needs to be clicked.
You could use driver.sleep() to check.
Hard to answer with your info, but these tips may help:
If you're getting no such element, try to verify the css selector or xpath you are using is correct. Firefox's Firebug Firefinder is an excellent tool for this. It will highlight the element your selector points to.
If your selector is correct, make sure you are using findElementsBy... and not findElementBy...
the plural version will return a list of webelements, from which you can then pull random elements to click on.
Use an intelligent wait to make sure the elements have loaded on the page. Sometimes selenium will try to interact with elements on the page before they appear. The selenium api has plenty of methods to help here, but if you're just debugging a quick Thread.sleep(5) when you load the page will work.

Why my test is throwing Exception-Unable to locate element in webdriver?

package testproject;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.*;
public class mytestclass {
public static void main(String[] args) {
WebDriver Driver = new FirefoxDriver();
Driver.get("https://www.gmail.com/");
WebElement wb= Driver.findElement(By.name("Email"));
wb.sendKeys("sweta");
WebElement wb1= Driver.findElement(By.name("Passwd"));
wb1.sendKeys("123456");
WebElement wb2= Driver.findElement(By.id("signIn"));
wb2.click();
WebElement wb3= Driver.findElement(By.xpath(".//*[#id='gb']/div[1]/div[1]/div[2]/div[5]/div[1]/a"));
wb3.click();
WebElement wb4= Driver.findElement(By.id("gb_71"));
wb4.click();
}
}
When i am executing this code everything is going fine till the point where i want the sign in button to be clicked. I am getting exception which says that
Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"xpath","selector":".//*[#id='gb']/div[1]/div[1]/div[2]/div[5]/div[1]/a"} but when i am trying to locate it using fierbug its working fine.
In the above mentioned code i changed the email id and password to keep the email safe.
I was facing problem with one more program which i already posted on stakwave so if u can then please have a look at this link-webdriver is not able to click on a hyperlink in firefox
Are you certain your page is completely loaded after you sign in?
Did you set a timeout for your webdriver? (how long it has to wait for elements). Probably it reads your html before it's completey loaded.
Webdriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
To find out quickly if this is the problem do Thread.sleep(8000) after you do wb2.click();
Remove the dot at the beginning of your xpath expression. That way you have an xpath expression thaty could match everything. With the dot at the beginning you might retrict yourself depending on if the current node is the root node or not. Ther eis no way to know it. Just the fact the dot can only give you trouble. Unfortunately you cannot always trust what tools like firebug give you (it is still true in 99% of the case).
Of course, ensure that the elemetns you are targeting are already on the screen as suggested by the previous answer.
I faced similar problem,
issue resolved after setting timeout.
Webdriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
Not sure whats the role of timeout here though.
remove the dot(.) and star(*) from the xpath and give proper tag name in place of star.
for example if #id=gb is the id of div element, place div in place of star.
Hope it will work.
//launch browser
FirefoxDriver driver = new FirefoxDriver(options);
driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
//gmail login :
driver.get("http://www.gmail.com");
driver.findElement(By.id("identifierId")).sendKeys("****",Keys.ENTER);
Thread.sleep(5000);
driver.findElement(By.id("password")).sendKeys("***",Keys.ENTER);
//logout:
driver.findElement(By.xpath("//div[#id='gb']/div[1]/div[1]/div[2]/div[4]/div[1]/a/span")).click();
Thread.sleep(5000);
driver.findElement(By.linkText("Sign out")).click();

Categories

Resources