Tuesday, 11 April 2023

Playwright: Count number of elements match to a selector

Locator.count() method return the number of elements matching given selector.

 

Signature

int count();

Example

int count = page.locator(".para").count();
 

Find the below working application.

countMatchingElements.html

<!DOCTYPE html>
<html>

<body>

	<p class="para">Paragraph1</p>
	<p class="para">Paragraph2</p>
	<p class="para">Paragraph3</p>

	<p>Paragraph4</p>
	<p>Paragraph5</p>

</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();
		}

	}
}

CountMatchingElements.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.Page;
import com.microsoft.playwright.Playwright;
import com.sample.app.util.FileUtil;

public class CountMatchingElements {

	public static void main(String[] args) throws IOException, InterruptedException {
		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 + "countMatchingElements.html");

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

			int count = page.locator(".para").count();
			System.out.println("Total matching elements with the class 'para' are : " + count);

			count = page.locator("p").count();
			System.out.println("Total paragraph elements are : " + count);
		}
	}

}

Output

Total matching elements with the class 'para' are : 3
Total paragraph elements are : 5


  

Previous                                                 Next                                                 Home

No comments:

Post a Comment