I am trying to automate an Angular 2.0 application.
HTML Code:
<input _hello="" class="myclass" formcontrolname="phoneCtrl" required="" sdcleave="" sdmutekeys="[0-9]" type="text" placeholder="Phone number">
When I try to locate above element using xpath
locator, it gives me below mentioned error.
Tried Code:
//input[@class='myclass'][0]
Error:no such element: Unable to locate element: {"method":"xpath","selector":"//input[@class='myclass'][0]"}(..)
Can anyone help me on this issue?
Maybe your DOM is not ready yet when Webdriver tries to locate element.
Add this code in a util.js
file :
util.js
'use strict';
/**
* Navigate to an url and wait some seconds
* @param {string} path The path
* @param {seconds} [seconds] The number of seconds to wait for
* @returns {Promise}
* @see waitSomeSeconds
*/
function navigateAndWait(path, seconds) {
return browser.get(path)
.then(function () {
return waitSomeSeconds(seconds);
});
}
/**
* Wait some seconds (default is 3)
* @param {int} [seconds]
* @returns {Promise}
*/
function waitSomeSeconds(seconds) {
return browser.sleep((seconds || 3) * 1000);
}
module.exports = {
navigateAndWait: navigateAndWait,
waitSomeSeconds: waitSomeSeconds
}
homepage.spec.js
'use strict';
var util = require('./util');
describe('Homepage test suite', function () {
it('should navigate to homepage', function() {
return util.navigateAndWait('/homepage');
});
it('should display title with correct data', function() {
expect(element(by.css('h1')).getText()).toBe('Welcome');
});
});
You would be better off using a CSS selector for something like this. XPath is not as widely supported and the performance is not as good as CSS selectors.
This should work
By.cssSelector("input[placeholder='Phone number']");
You should spend some time learning about CSS selectors. They are very powerful locators and, in my experience, can be used in 99% of locators successfully.
CSS Selector Reference
CSS Selector Tips
Xpath indexes start with 1 and not 0 and that's the reason webdriver is throwing an error.
Correct XPath Would be
//input[@class='myclass'][1]
For example for the following XPath to find google search box won't give you any Element.
//*[@id='lst-ib'][0]
but following would just work fine
//*[@id='lst-ib'][1]
Use the tool like https://addons.mozilla.org/en-US/firefox/addon/firebug/ and https://addons.mozilla.org/en-us/firefox/addon/firepath/ to check if you XPath is valid or not.
Try this way using xpath locator
Explanation: Use placeholder
attribute of <input>
tag.
//input[@placeholder='Phone number']
In java
You can do this way.
driver.findElement(By.xpath("//input[@placeholder='Phone number']")).sendKeys("1234567890");