Selenium Webdriver lets us locate elements in a web page in many different ways. Some of them are:
By id: If the HTML element to be located has a unique id one can use this id to locate the element in the code. Java statement for this will be as below:
driver.findElement(By.id(“id here”));
By Name: Similarly, if the element has a unique name once can use following code statement:
driver.findElement(By.name("element name here"));
In both the above cases if multiple elements have duplicate id or name then the first element will be selected.
By XPath: XPath expressions are very powerful to locate elements but there is a learning curve involved. An example: Suppose we have this HTML code:
<div name="outer"> <div id="inner1"> <span>Inner 1</span> <span><input name="ip1" class="c1 c2 c3" /></span> </div> <div id="inner2"> <span>Inner 2</span> <span><input name="ip2" class="c1 c3 c5" /></span> </div> <div id="inner3"> <span>Inner 3</span> <span><input name="ip3" class="c3 c2 c6" /></span> </div> </div>
And we want to find 3rd input box with name “ip3” with XPath expressions. There can be multiple ways to create the expression some of which are mentioned below:
//div/div[3]/span/input >> Means inside first div, locate 3rd div, inside it locate span and inside it locate input element which is for ip3 //input[@name='ip3'] >> directly locate input box with name “ip3” (//div[@name='outer']//input)[3] >> 3rd input box under div with name “outer” //input[contains(@class,'c6')] >> find on the basis of unique CSS class name
Java call would look like this:
driver.findElement(By.xpath("//input[contains(@class,'c6')]"));
By CSS – With CSS we can locate elements, like in previous example, we can use this code statement to locate last input box:
driver.findElements(By.css("input[class~='c6']"));
By text to find hyperlink elements – If an ahref element is to be located then one can use find by a linkText method. For example, see this HTML code:
<a href="mypage.htm">My page</a>
This Java statement will find it:
driver.findElement(By.linkText("My page"));
If we need to find an element in a page using a portion of a text, then partialLinkText() can be used.