Introduction
In Selenium WebDriver, locators are used to identify elements on a webpage. The findElement() to find a single element and findElements() to find multiple elements. There are multiple ways to uniquely identify a web element within the web page such as ID, CSS Selector, XPATH, Name, Class Name, Tag Name, Link Text, And Partial Link Text.
FindElement(): method returns a single element or throws an exception if none is found.
Syntax
WebElement elementName = driver.findElement(By.LocatorStrategy("ValueOfLocators"));
Below are some examples of Locator Strategy
1. Id: Finds elements with an Id attribute that includes the specified value.
WebElement elementId = driver.findElement(By.id("header_block"));
2. CSS Selector: Locates elements matching a CSS selector.
WebElement elementSelector =driver.findElement(By.cssSelector("input[type='submit']"));
3. Xpath: Locates elements matching an Xpath expression.
WebElement elementXpath =driver.findElement(By.xpath("//input[@type='submit']"));
4. Name: Finds elements with a name attribute that includes the specified value.
WebElement elementName =driver.findElement(By.name("nameValue"));
5. ClassName: Finds elements with a class name attribute that includes the specified value.
WebElement elementClassName =driver.findElement(By.className ("classValue"));
6. TagName: Select elements by their HTML tag.
WebElement elementTagName =driver.findElement(By.tagName ("html tagName"));
7. LinkText: Finds links by their exact text.
WebElement elementLinkText =driver.findElement(By.linkText ("Text in the Link"));
8. Partial LinkText: Locates anchor elements whose visible text contains the search values. If multiple elements are matching, only the first one will be selected.
WebElement elementPartialLinkText = driver.findElement(By.partialLinkText ("Partial Text in the Link"));
findElements(): method returns a list of matching elements, or an empty list if none are found.
Syntax
List<WebElement> listOfElements = driver.findElements(By.xpath("//div"));
Below are some examples of ID
List<WebElement> elements = driver.findElements(By.id("globalContainer"))
Comments
Post a Comment