LOCATING AN ELEMENT

Locators

There are different locators that are used in selenium to locate an element, Any element can be stored using WebElement interface. The locators used are:
  1. ID
  2. Name
  3. Link Text
  4. Partial Link Text
  5. Xpath
  6. CSSSelector
Let us discuss them in detail:

How can we locate an element by ID?

we are trying to book a flight ticket from Yatra.com website. To book, we need to search a flight & while searching a flight, we need to provide the details of From, To, Depart, Return and Passenger count. If we need to automate this functionality, we can identify these elements using the ID. Please find the screenshot below:


From the above screen you can see that the element 'From' can be detected by its ID 'BE_flight_origin_city'. So to detect the element, we write:
WebElement element = driver.findElement(By.id("BE_flight_origin_city"));
Here driver is an instance of 'WebDriver' interface.

How can we locate an element by 'Name'?

From the above example you can also find an HTML attribute 'name' for the selected element as shown below:
From the above screen you can see that the element 'From' can be detected by its Name 'flight_origin_city'. So to detect the element, we write:
WebElement element = driver.findElement(By.name("flight_origin_city"));
Here driver is an instance of 'WebDriver' interface.

How can we locate an element by 'Link Text'?

If we want to click on a specific link/hyperlink in a page, we do it using LinkText. For e.g., we want to click on the link 'Delhi to Mumbai flights' link in yatra website home page (find the screenshot below)
To identify this element from the page we would write the following:
WebElement element = driver.findElement(By.linkText("Delhi to Mumbai Flights"));
Here driver is an instance of 'WebDriver' interface.

How can we locate an element by 'Partial Link Text'?

If we want to find all the elements with a specific title in a page, we do it using Partial Link Text. For e.g., we want to check how many links are present with title 'Flights' in yatra website home page (find the screenshot below).
To identify these elements from the page we would write the following:
List<WebElement> list = driver.findElements(By.partialLinkText("Flights"));
Here driver is an instance of 'WebDriver' interface,
As there can be multiple links we use the method 'findElements' instead of 'findElement',
and we are using List<WebElement> instead of WebElement to store all the links found.

We will be discussing about xpath and css selector in future posts.

Comments

Popular posts from this blog

BEGINNING WITH SELENIUM

Setting up Maven in Eclipse editor

SELENIUM