How to Locate Web Elements with Selenium WebDriver?

In order to write UI tests with Selenium WebDriver you need to be able to identify web page elements fast and in an accurate way. You don’t want to revisit these selectors very often so you must choose the right selector from the beginning.

There are some browser tools that you can use in order to identify web elements in the DOM easier. These are:

  • Firebug for Firefox
  • Google Developer Tools for Chrome
  • Web Inspector for Safari

Selenium WebDriver API supports different possibilities to identify elements: by ID, by CLASS, by NAME, by CSS selector, by XPath, by TAG name. Also you define your custom selector in order to interact with the elements.

It’s always a good practice to assign unique IDs to elements, also names and classes in order to be more usable for automatic UI tests. If that is not possible you’ll need to use advanced or XPath selector to interact with those elements. The most popular selectors are the CSS selectors due to performance and simplicity reasons.

To inspect an element you just have to open the desired web page, right-click the desired element and click on Inspect Element. A new panel will open showing the desired element. Also you can inspect other elements by clicking on the cursor in the top left side of the Developer Tools or Firebug panels and hovering page elements.

Locating Elements with Selenium WebDriver, findElement() method returns and WebElement and findElements() returns a list of WebElements.

1. By ID:

1
in Java: driver.findElement(By.id("element id"))

2. By CLASS:

1
in Java: driver.findElement(By.className("element class"))

3. By NAME:

1
in Java: driver.findElement(By.name("element name"))

4. By TAGNAME:

1
in Java: driver.findElement(By.tagName("element html tag name"))

5. By CSS Selector:

1
in Java: driver.findElement(By.cssSelector("css selector"))

6. By Link:

1
in Java: driver.findElement(By.link("link text"))

7. By XPath:

1
in Java: driver.findElement(By.xpath("xpath expression"))

Let’s get a HTML snippet code and see how can we use these Selenium WebDriver selectors in order to identify the desired elements:

1
2
3
4
5
6
7
8
9
10
<div class="thumbnail center well well-small text-center">
<h2>Newsletter</h2>
Subscribe to our weekly Newsletter and stay tuned.
<form action="" method="post" name="subscribe"><label for="name">Name: </label>
 <input class="name" id="name" type="text" placeholder="Enter name..." />
 <label for="email">Email: </label> <input class="email" id="email" type="text" placeholder="[email protected]" />
 <input class="btn btn-large" type="submit" value="Subscribe" /></form>
 <a title="first link" href="#link1">First Link</a>
 <a title="second link" href="#link2">Second Link</a>
</div>

Let’s get some WebElements from the above HTML code snippet:

1
WebElement nameInputField = driver.findElement(By.id("name"));

or

1
WebElement nameInputField = driver.findElement(By.className("name"));

or

1
WebElement emailInputField = driver.findElement(By.id("email"));

Locate link elements with findElements() method from the HTML snipped

1
2
3
4
5
6
7
8
@Test
public void findLinksTest(){
   //Get all the links displayed
   List links = driver.findElements(By.tagName("a"));
   assertEquals(2, links.size());
   for(WebElement link : links)
   System.out.print(link.getAttribute("href"));
}

Locate link elements from the HTML snipped:

How to find a link with Selenium WebDriver API by full text:

1
2
WebElement firstLink = driver.findElement(By.linkText("First Link"));
assertEquals("#link1", firstLink.getAttribute("href"))

How to find a link with Selenium WebDriver API by partial text:

1
2
WebElement firstLink = driver.findElement(By.partialLinkText("First"));
assertEquals("#link1", firstLink.getAttribute("href"))

Locate elements by HTML Tag Name:

1
WebElement subscribeButton = driver.findElement(By.tagName("button"));

Locate elements by CSS Selectors

1
2
WebElement emailInputField =
           driver.findElement(By.cssSelector("form input#email"));

or

1
2
WebElement emailInputField =
           driver.findElement(By.cssSelector("input.email"));

or

1
2
WebElement emailInputField =
           driver.findElement(By.cssSelector("input[type='submit'][value='Subscribe']"));

Performing partial match on attribute values

1
^= as in input[id^='email'] means Starting with.

 

1
$= as in input[id$='_name'] means Ending with.

 

1
*= as in Input[id*='userName'] means Containing.

Finding elements with XPATH

  • Absolute path
1
2
WebElement userName =
           driver.findElement(By.xpath("html/body/div/form/input"));
  • Relative path
1
WebElement email = driver.findElement(By.xpath("//input"));

Finding elements using index

1
2
WebElement email =
           driver.findElement(By.xpath("//input[3]"));

Finding elements using attributes values with XPath

1
2
WebElement logo =
           driver.findElement(By.xpath("img[@alt='logo']"));

XPATH

1
2
3
starts-with()
 
input[starts-with(@id,'input')]

Starting with:

1
2
3
ends-with()
 
input[ends-with(@id,'_field')]

Ending with:

1
2
3
contains()
 
input[contains(@id,'field')]

Containing

Locating table rows and cells

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Test
public void testTable() {
   WebElement simpleTable = driver.findElement(By.id("items"));
 
   //Get all rows
   List rows = simpleTable.findElements(By.tagName("tr"));
   assertEquals(3, rows.size());
 
   //Print data from each row
   for (WebElement row : rows) {
      List cols = row.findElements(By.tagName("td"));
      for (WebElement col : cols) {
         System.out.print(col.getText() + "\t");
      }
   System.out.print();
   }
}

Using jQuery selectors

Locate all the Checkbox which are checked by calling jQuery find() method.
find() method returns elements in array

1
2
List elements =
        (List) js.executeScript("return jQuery.find(':checked')");

Refer: https://loadfocus.com/blog/2013/09/how-to-locate-web-elements-with-selenium-webdriver/
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章