One of the best things about Selenium is the flexibility of the library.
You can see it in many places, for example, in locators.
It is possible to locate an element by id, and name, and class name, and xpath, and css and a few others ways.
It is possible to load a site in 2 different ways.
It is possible to synchronize the test with an element in many different ways.
But when it comes to finding an element, what are all options?
How many do you know of?
If your answer is 2, it is too low.
Let’s see how you can find a web element with Selenium.
1. the page factory way
The page class uses FindBy annotations and web element fields that are initialized in the page class constructor. The elements are found automatically before they are used the first time.
public class LoginPage {
private WebDriver driver;
@FindBy(name="uid")
private WebElement userNameBox;
@FindBy(name="password")
private WebElement passwordBox;
@FindBy(name="btnLogin")
private WebElement loginButton;
public LoginPage(WebDriver driver){
this.driver = driver;
PageFactory.initElements(driver, this);
}
public void setUserName(String userName){
userNameBox.sendKeys(userName);
}
public void setPassword(String password){
passwordBox.sendKeys(password);
}
public void clickLogin(){
loginButton.click();
}
2. using the findElement() method of the driver
WebElement button = driver.findElement(buttonXpath);
3. using the findElements() method of the driver
List<WebElement> buttons = driver.findElements(buttonXpath);
button = buttons.get(0);
4. using the findElement() method for a web element
WebElement span = driver.findElement(spanXpath);
WebElement link = span.findElement(linkXpath);
5. using the findElements() method for a web element
WebElement span = driver.findElement(spanXpath);
List<WebElement> links = span.findElements(linkXpath);
WebElement link = links.get(0);
6. using an explicit wait and an expected condition that returns a web element
WebElement button = wait.until(
ExpectedConditions.elementToBeClickable(
buttonXpath));
7. using an explicit wait and an expected condition that returns a list of web elements
List<WebElement> buttons = wait.until(
ExpectedConditions.numberOfElementsToBeMoreThan(
buttonXpath, 0));
button = buttons.get(0);
8. using JavaScript
WebElement button = (WebElement)jsExecutor.executeScript(
"return document.querySelector(\"input[id = 'edit-keyword']\");");
There are 8 ways of finding an element using the SELENIUM library.
If one does not work, you can try in other ways.