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

Selenium Grid - Distributed Systems

Selenium grid is powerful and can be easily used with just few lines of code. A Grid is a network of computers which can be heterogeneous and geographically dispersed. A Selenium Grid is how a grid of computers are connected using Selenium and configured to perform a task. A task typically here is running a suite of test cases with different browsers in different platforms across geographically dispersed systems. The test cases can be run in parallel using Selenium. So if we have a grid of three computers the same set of test cases can be run in IE, Firefox and Chrome. To establish this we have three important components. 1) Hub 2) Node 3) Test Script A Hub acts like the server to which requests are sent . The Hub sends to request to various registered nodes. The HUB can be instantiated using command line by using the selenium server standalone jar file. Open command prompt, navigate to the folder which has the selenium server file and use this command. java -jar selen...

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...

Transition from Test Automation Engineer to Test Engineer

What's the difference? Test Automation Engineer works on automating the Regression Test Suite. Test Engineer ensures the product can be released to the customer. With my industry experience, I have realized, that, as part of automation engineer your job duties don't stop with creating Automation tests, Frameworks and running them. With more tests being automated, your responsibilities not only include running the complete Regression suite but occasionally validation and verification of the product. There are different documents/sites defining different types of testing and where their usage, however,but finding bugs is a different skill. Though we are testers by role, our analytical minds work like developers as we develop scripts too. We could be biased. When something doesn't work, we look for a workaround and think it's no big deal. This attitude is a deal breaker!Instead use your skills to analyse and break the code. Here I am going to list some of my ideas ...