Monday, 2 June 2014

Finding elements using the CSS selector .

Finding elements using ID selector:

WebElement userName = driver.findElement(By.cssSelector("input#username"));

There is also a shortcut where you can enter # and a id attribute value and ignore the
HTML tag. Like,
WebElement userName = driver.findElement(By.cssSelector("#username"));

Finding elements using Class selector:

WebElement loginButton = driver.findElement(By.cssSelector("input.login"));
This will find the Login button's <input> tag whose Class attribute is login.
There is also a shortcut where you can put a . and class attribute value and ignore the HTML
tag.
WebElement loginButton = driver.findElement(By.cssSelector(".login"));

using attributes selector:

WebElement userName = driver.findElement(By.cssSelector("input[name=username]"));
 Using the name attribute to locate an element is similar to the name() locator method of the
By class.

Let's use some other attribute to locate an element. In the following example, the <img>

element is located by using its alt attribute.
WebElement previousButton =
driver.findElement(By.cssSelector("img[alt='Previous']"));

You might come across situations where one attribute may not be sufficient to locate an

element and you need to combine additional attributes for a precise match.

example, multiple attributes are used to locate the Login button's <input> element:

WebElement previousButton = driver.findElement(By.cssSelector("input[t
ype='submit'][value='Login']"));


No comments:

Post a Comment