Watch my video on this concept in my Youtube Channel QtpSudhakar
package org.qtpsudhakar.Selenium4Features;
import java.time.Duration;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.locators.RelativeLocator;
import io.github.bonigarcia.wdm.WebDriverManager;
public class RelativeLocatorsExample2 {
public static void main(String[] args) throws InterruptedException {
// setup driver
WebDriverManager.chromedriver().setup();
// open browser
WebDriver driver = new ChromeDriver();
// maximize window
driver.manage().window().maximize();
// specify timeout
driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(10));
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
// navigate to URL
driver.get("https://opensource-demo.orangehrmlive.com/index.php/auth/login");
// login
driver.findElement(By.id("txtUsername")).sendKeys("Admin");
driver.findElement(By.id("txtPassword")).sendKeys("admin123");
driver.findElement(By.id("btnLogin")).click();
// click on PIM Link
driver.findElement(By.linkText("PIM")).click();
//Click on Checkbox based on ID
String empId = "0002";
// Using Relative Locator to find checkbox besides employee ID
driver.findElement(RelativeLocator.with(By.tagName("input")).toLeftOf(By.linkText(empId))).click();
getHorizontalInlineElement(driver, By.tagName("input"), By.linkText("0002")).click();
}
public static WebElement getHorizontalInlineElement(WebDriver driver, By dynamicElement, By uniqElm) {
/* without using java stream
// Get list of matching elements
List lst = driver.findElements(dynamicElement);
// Get Y Axis of Related Element
int y = driver.findElement(uniqElm).getRect().getY();
// Navigate to all located elements to find element in line
for (WebElement elm : lst) {
if (Math.abs(elm.getLocation().getY() - y) <= 10) {
return elm;
}
}
*/
//Using Java Stream to filter elements with + or - 10 pixel horizontal and get first element
return driver.findElements(dynamicElement).stream()
.filter(t -> Math.abs(t.getLocation().getY() - driver.findElement(uniqElm).getRect().getY()) <= 10)
.findFirst().get();
}
public static WebElement getVerticalInlineElement(WebDriver driver, By dynamicElement, By uniqElm) {
return driver.findElements(dynamicElement).stream()
.filter(t -> Math.abs(t.getLocation().getX() - driver.findElement(uniqElm).getRect().getX()) <= 10)
.findFirst().get();
}
}
No comments :
Post a Comment