Skip to main content

How to find a WebElement

Find Element & Find Elements Method

The difference between “Find Element” and “Find Elements” method is the first returns a WebElement object otherwise it throws an exception and the latter returns a list of WebElements, it can return an empty list if no DOM elements match the query. The “Find” methods take a locator or query object called “By”. “By” methods are listed below.

By ID

With this strategy, the first element with the id attribute value matching the location will be returned. If no element has a matching id attribute, a NoSuchElementException will be raised. This is the most efficient and preferred way to locate an element, as most of the times IDs are unique. But in some cases UI developers make it having non-unique ids on a page or auto-generating the id, in both cases it should be avoided.
Example: If an element is given like this:
<input id=”username”></input>
WebElement we=driver.findElement(By.id(“username”));
 we.sendkeys("type your string here");
import org.openqa.selenium.Keys can be used to enter special keys like
we.sendKeys(Keys.RETURN);
we.sendKeys(Keys.TAB);


By Name

This is also an efficient way to locate an element but again the problem is same as with ID that UI developer make it having non-unique names on a page or auto-generating the names. With this strategy, the first element with the name attribute value matching the location will be returned. If no element has a matching name attribute, a NoSuchElementException will be raised.
Example: If an element is given like this:
<input id =”userID” name=”username”></input>
WebElement we=driver.findElement(By.name(“username”));

By Class Name

With this you can find elements based on the value of the “class” attribute. If an element has many classes then this will match against each of them. A class can contain many elements.
Example: If an element is given like this:
<span class=”catfish”></span>
WebElement we=driver.findElement(By.classname(“catfish”));


By Tag Name

With this you can find elements by their tag names.
Example: If an element is given like this:
<dt> <a href="select_tag.html">Tag Selected</a> </dt>
WebElement element=driver.findElement(By.tagName("dt"));

By Link Text

With this you can find elements of “a” tags(Link) with the link names. Use this when you know link text used within an anchor tag.
Example: If an element is given like this:
<a href="link.html">Name of the Link</a>
WebElement element=driver.findElement(By.linkText("Name of the Link"));

By Partial Link Text

With this you can find elements of “a” tags(Link) with the partial link names. Use this when you know link text used within an anchor tag.
Example: If an element is given like this
<a href="link.html">Name of the Link</a>
WebElement element=driver.findElement(By.partialLinkText("Name of"));


Dom Locator

The DOM strategy works by locating elements that matches the JavaScript expression referring to an element in the DOM of the page. DOM stands for Document Object Model. DOM is convention for representing objects in HTML documents.
Example: 
document.forms[0].elements[0]
document.forms['loginForm'].elements['username']
document.forms['loginForm'].username
document.getElementById(‘username’)

JavascriptExecutor js = (JavascriptExecutor) driver;
String script = "return document.getElementById('example');";
WebElement exampleDiv = (WebElement) js.executeScript(script);
exampleDiv.getText();
 js.executeAsyncScript(script);  - This line is for AJAX script
Finding all the input elements to the every label on a page:
List<WebElement> labels = driver.findElements(By.tagName("label"));
List<WebElement> inputs = (List<WebElement>) ((JavascriptExecutor)driver).executeScript(
    "var labels = arguments[0], inputs = []; for (var i=0; i < labels.length; i++){" +"inputs.push(document.getElementById(labels[i].getAttribute('for'))); } return inputs;", labels);

By CSS Selector

Like the name implies it is a locator strategy by css. Native browser support is used by default, so please refer to w3c css selectors <http://www.w3.org/TR/CSS/#selectors> for a list of generally available css selectors. Beware that not all browsers were created equal, some css that might work in one version may not work in another.
Example of to find the cheese below:
<div id=”food”><span class=”diary”>milk</span><span class=”diary aged”>cheese</span></div>
WebElement cheese=driver.findElement(By.cssSelector(“#food span.diary.aged”);

XPath Locator

While DOM is the recognized standard for navigation through an HTML element tree, XPath is the standard navigation tool for XML; and an HTML document is also an XML document (xHTML). XPath is used everywhere where there is XML.
Example: To select the username from the above example you can use the following ways:
xpath=//*[@id='username']
xpath=//input[@id='username']
xpath=//form[@name='loginForm']/input[1]
xpath=//*[@name='loginForm']/input[1]


Comments

Popular posts from this blog

Switch between browsers\windows and pop ups

These commands can be used to switch between windows, iterate through different windows opened by the webdriver, handle pop ups and frames in windows.  GetWindowHandle Command Purpose : To get the   window handle   of the current window. driver.getWindowHandle(); Returns an alphanumeric string GetWindowHandles Command Purpose : To get the   window handle   of   all   the current windows. Set<String> handle=Driver.getWindowHandles(); Returns a set of window handles SwitchTo Window Command Purpose : WebDriver supports   moving   between named windows using the “switchTo” method. For(String handle:driver.getWindowHandles()) Driver.switchto().window(handle); Or Driver.switchto().window(windowname); <A href="newwindow.html" target=" windowname ">click here for a new window </A> SwitchTo Frame Command Purpose : WebDriver supports moving between frames using the “ switchTo ” method. Driver.s...

Selenium - What Why Who How?

What is Selenium? Selenium is an open source automated   testing   suite for web applications across different browsers and platforms.   It is quite similar to HP Quick Test Pro ( QTP ) only that Selenium focuses on automating web-based applications. Why use Selenium? Selenium is fast and it supports programming in multiple languages like Java, C#,Python and Ruby.  So development of automation scripts can be done in your language of preference. Selenium works well with AJAX testing. Selenium Grid supports execution of test cases in multiple platforms and multiple browsers in remote systems as well.  The support for different programming languages gave selenium the power to harness the capabilities of those programming languages .  For example, using JAVA as the programming language to code selenium scripts enables selenium to use JDBC for database access and testing.All the APIs supported in Java also become the advantage of Selenium like L...