How to use RelativeLocator class of org.openqa.selenium.support.locators package

Best Selenium code snippet using org.openqa.selenium.support.locators.RelativeLocator

Run Selenium automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

copy
1package day3;
2
3import java.util.List;
4
5import org.openqa.selenium.By;
6import org.openqa.selenium.WebElement;
7import org.openqa.selenium.chrome.ChromeDriver;
8import org.openqa.selenium.support.locators.RelativeLocator;
9import org.openqa.selenium.support.locators.RelativeLocator.RelativeBy;
10
11import static org.openqa.selenium.support.locators.RelativeLocator.withTagName;
12import static org.openqa.selenium.By.id;
13
14
15public class LearnLocators {
16
17	public static void main(String[] args) {
18
19		// Set the ChromeDriver Exe Path
20		System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe");
21
22		// Launch your browser
23		ChromeDriver driver = new ChromeDriver();
24		
25		// 
26		driver.get("http://leafground.com/pages/sorttable.html");
27
28		// Find the new way
29//		WebElement thisElement = driver.findElement(RelativeLocator.withTagName("button").above(By.xpath("//*[text()='Get Position']")));
30		/*WebElement thisElement = driver.findElement(
31				RelativeLocator.withTagName("button").
32				below(By.xpath("//*[text()='Get Position']")));*/
33		
34/*		driver.findElement(id(""));
35*/		
36		
37		/*driver.findElement(RelativeBy.);
38		*/
39		/*List<WebElement> allBelowElements = driver.findElements(
40				RelativeLocator.withTagName("*").
41				below(By.xpath("//*[text()='Get Position']")));
42		
43		// Print the text of the element
44		for (WebElement thisElement : allBelowElements) {
45			System.out.println(thisElement.getText());
46		}
47		*/
48		
49	
50		/*List<WebElement> belowElements = driver.findElements(RelativeLocator
51				.withTagName("input")
52				.above(By.xpath("//label[text()='Clear the text']")));
53		
54		System.out.println(belowElements.size());
55		for (WebElement ele : belowElements) {
56			System.out.println(ele.getAttribute("name"));
57			ele.clear();
58		}*/
59		
60		/*List<WebElement> elements = driver.findElements(RelativeLocator
61				.withTagName("td")
62				.toRightOf(By.xpath("//td[text()='100%']")));
63		
64		
65		System.out.println(elements.size());
66		for (WebElement ele : elements) {
67			System.out.println(ele.getText());
68		}*/
69		
70		
71		
72		List<WebElement> belowElements = driver.findElements(RelativeLocator
73				.withTagName("td")
74				.toRightOf(By.xpath("//td[text()='1001']")));
75		
76		System.out.println(belowElements.size());
77		
78		
79		
80		
81		for (WebElement ele : belowElements) {
82			System.out.println(ele.getText());
83			
84		}	
85		
86		
87
88	}
89
90	
91
92}
93
Full Screen
copy
1package pages;
2
3import org.openqa.selenium.*;
4import org.openqa.selenium.support.FindBy;
5import org.openqa.selenium.support.PageFactory;
6import org.openqa.selenium.support.locators.RelativeLocator;
7import static org.openqa.selenium.support.locators.RelativeLocator.withTagName;
8
9public class ScaleFocusHomePage {
10
11    protected WebDriver driver;
12
13    public ScaleFocusHomePage(WebDriver driver) {
14        this.driver = driver;
15        PageFactory.initElements(driver, this);
16    }
17
18    // SELECTORS
19    @FindBy(css = ".icons-menu .icon-share.open-share")
20    protected WebElement shareNavigationIcon;
21    @FindBy(className = "search-container")
22    protected WebElement searchContainer;
23    @FindBy(css = ".gtm-hp-vmbtn-serv.view-more-btn")
24    protected WebElement servicesViewMoreButton;
25    @FindBy(css = ".desciprtion .h3-p")
26    protected WebElement descriptionServicesParagraph;
27
28    // METHODS
29    public void clickSearchIconFromNavigation() {
30        // Click to right of Careers in the Navigation drop down menu
31        driver.findElement(RelativeLocator.withTagName("i")
32                .toLeftOf(shareNavigationIcon))
33                .click();
34    }
35
36    public String getSearchContainerAttribute(String attribute) {
37        // Return element's passed attribute
38        return searchContainer.getAttribute(attribute);
39    }
40
41    public void clickCloudServicesViewMoreButton() {
42        // To remove "RelativeLocator." use: import static org.openqa.selenium.support.locators.RelativeLocator.withTagName;
43        driver.findElement(withTagName("span")
44                .toRightOf(servicesViewMoreButton)
45                .below(descriptionServicesParagraph))
46                .click();
47    }
48}
Full Screen
copy
1package io.testproject.blog11selenium4relativelocators;
2
3import static org.openqa.selenium.support.locators.RelativeLocator.*;
4import static org.openqa.selenium.support.locators.RelativeLocator.withTagName;
5
6import org.openqa.selenium.WebDriver;
7import org.openqa.selenium.support.locators.RelativeLocator;
8import org.testng.annotations.Test;
9
10public class DifferentImportStatements {
11
12	WebDriver driver;
13	
14	@Test
15	public void useRelativeLocatorInSyntax () {
16		driver.findElement(RelativeLocator.withTagName(""));
17	}
18	
19	@Test
20	public void skipRelativeLocatorInSyntax () {
21		driver.findElement(withTagName(""));
22	}
23}
24
25
Full Screen
copy
1driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
2
Full Screen
copy
1Warning: (143,13) 'WebDriverWait(org.openqa.selenium.WebDriver, long)' is deprecated
2
Full Screen
copy
1v4.0.0-alpha-3
2==============
3
4* Add "relative" locators. The entry point is through the `RelativeLocator`.
5  Usage is like `driver.findElements(withTagName("p").above(lowest));`
6* Add chromedriver cast APIs to remote server (#7282)
7* `By` is now serializable over JSON.
8* Add ApplicationCache, Fetch, Network, Performance, Profiler,
9  ResourceTiming, Security and Target CDP domains.
10* Fixing Safari initialization code to be able to use Safari Technology
11  Preview.
12* Ensure that the protocol converter handles the new session responses
13  properly.
14* Expose devtools APIs from chromium derived drivers.
15* Expose presence of devtools support on a role-based interface
16* Move to new Grid, deleting the old standalone server and grid implementation.
17* Switch to using `HttpHandler` where possible. This will impact projects that
18  are extending Selenium Grid.
19* Respect "webdriver.firefox.logfile" system property in legacy Firefox driver.
20  Fixes #6649
21* Back out OpenCensus support: OpenTracing and OpenCensus are merging, so
22  settle on one for now.
23* Only allow CORS when using a —allow-cors flag in the Grid server
24* If you're using the Java Platform Module System, all modules
25  associated with the project are generated as "open" modules. This
26  will change in a future release.
27* The version of Jetty being used is unshadowed.
28
Full Screen
copy
1driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
2
Full Screen
copy
1driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
2
Full Screen
copy
1WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
2
Full Screen
copy
1import java.time.Duration;
2
3        driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
4        driver.manage().timeouts().scriptTimeout(Duration.ofSeconds(30));
5        driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(60));
6
Full Screen
copy
1@Deprecated
2public WebDriverWait(WebDriver driver, long timeoutInSeconds) {
3    this(driver, Duration.ofSeconds(timeoutInSeconds));
4}
5
Full Screen
copy
1new WebDriverWait(driver, Duration.ofSeconds(10));
2
Full Screen
copy
1By locatorBase = By.xpath("./div/div[contains(@class,'listRoot')]";
2By relativeLocator = getNthZElementLocator("2");
3ByChanged chainedLocator = new ByChained(locatorBase, relativeLocator);
4
Full Screen
copy
1String XPATH_Z_ELEMENT_STRING = ".//ul/li[%s]";
2public By getNthZElementLocator(String replaceArg)
3{
4    return By.xpath(String.format(XPATH_Z_ELEMENT_STRING, replaceArg));
5}
6
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Most used methods in RelativeLocator

Run Selenium Automation Tests on LambdaTest Cloud Grid

Trigger Selenium automation tests on a cloud-based Grid of 3000+ real browsers and operating systems.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)