Monday, 29 May 2023

Playwright: Get the locator by ARIA role

'page.getByRole()' method locate the elements by their ARIA role.

 

Signature

Locator getByRole(AriaRole role)
Locator getByRole(AriaRole role, GetByRoleOptions options)

 

Example

ElementHandle elementHandle = page.getByRole(AriaRole.BANNER).elementHandle();

 

Find the below working application.

 

ariaRoles.html

<html>

<head>
	<title>ARIA roles example</title>
</head>

<body>
	<h1 role="banner" id="myBanner" class="headerSection">This is page banner</h1>

	<div role="contentinfo">
		blog: https://self-learning-java-tutorial.blogspot.com/
	</div>

</body>

</html>

 

FileUtil.java

package com.sample.app.util;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class FileUtil {

	public static String resourceAsString(String resourceName) throws IOException {
		ClassLoader classLoader = FileUtil.class.getClassLoader();
		URL url = classLoader.getResource(resourceName);
		if (url == null) {
			return null;
		}

		URLConnection urlConnection = url.openConnection();

		urlConnection.setUseCaches(false);

		try (InputStreamReader inputStreamReader = new InputStreamReader(urlConnection.getInputStream())) {
			char[] buffer = new char[1048];
			StringBuilder builder = new StringBuilder();

			int count = -1;
			while ((count = inputStreamReader.read(buffer, 0, buffer.length)) != -1) {
				builder.append(buffer, 0, count);
			}

			return builder.toString();
		}

	}
}

 

GetLocatorByAriaRoles.java

package com.sample.app.locators;

import java.io.File;
import java.io.IOException;

import com.microsoft.playwright.Browser;
import com.microsoft.playwright.BrowserType;
import com.microsoft.playwright.ElementHandle;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.Playwright;
import com.microsoft.playwright.options.AriaRole;
import com.sample.app.util.FileUtil;

public class GetLocatorByAriaRoles {
	public static void main(String[] args) throws IOException {
		try (Playwright playwright = Playwright.create()) {

			Browser browser = playwright.chromium()
					.launch(new BrowserType.LaunchOptions().setHeadless(false).setSlowMo(100));

			final String content = FileUtil.resourceAsString("locators" + File.separator + "ariaRoles.html");

			Page page = browser.newPage();
			page.setContent(content);

			ElementHandle elementHandle = page.getByRole(AriaRole.BANNER).elementHandle();

			String role = elementHandle.getAttribute("role");
			String id = elementHandle.getAttribute("id");
			String clazz = elementHandle.getAttribute("class");

			System.out.println("role : " + role);
			System.out.println("id : " + id);
			System.out.println("class : " + clazz);
		}
	}
}

 

Output

role : banner
id : myBanner
class : headerSection

 

 

 

Previous                                                 Next                                                 Home

No comments:

Post a Comment