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

How to Install Selenium and execute your first program

You can install and test Selenium using the following steps. All files can be downloaded from  http://www.seleniumhq.org/download/   Download Selenium Server jar file   Download client library java jar file   Download InternetExplorer Driver file   Install eclipse workspace. (download eclipse. Unzip folder. Find eclipse.exe application and open it) Create a new java project with 1,2 as references Copy 3 to workspace For IE, go to internet options->security and change the security level so that it’s the same for all zones. Write sample java program Below program opens google in IE and searches for selenium test and closes it. // All the imports happen automatically when you use eclipse ide and add the downloaded jars in the project references package test; import org.openqa.selenium.Alert; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.ie...

Form - User Input Automation

Text boxes WebElement t=driver.findElement(By.id(“username”)); t.sendkeys(“test name”); Buttons WebElement t=driver.findElement(By.id(“createbutton”)); t.click(); DropDown Boxes  WebElement select = driver.findElement(By.tagName("select")); List<WebElement> allOptions = select.findElements(By.tagName("option")); for (WebElement option : allOptions) { System.out.println(String.format("Value is: %s", option.getAttribute("value"))); option.click(); } This will find the first “SELECT” element on the page, and cycle through each of its OPTIONs in turn, printing out their values, and selecting each in turn. As you will notice, this isn’t the most efficient way of dealing with SELECT elements. WebDriver’s support classes include one called “Select”, which provides useful methods for interacting with these Select oSelection = new Select(driver.findElement(By.tagName("select"))); oSelection.deselectAll(); //All op...

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