Monday, 5 June 2023

Playwright: Get the locator by title

page.getByTitle() method locate the elements that match to given title.

 

Signature

Locator getByTitle(String text)
Locator getByTitle(String text, GetByTitleOptions options)
Locator getByTitle(Pattern text)
Locator getByTitle(Pattern text, GetByTitleOptions options)

Example

String text = page.getByTitle("para1").textContent();

Find the below working application.

 

titleDemo.html

<!DOCTYPE html>
<html>

<body>

	<h1>Get the locator by demo</h1>

	<p title="para1">Paragraph 1</p>
	<p title="para2">Paragraph 2</p>
	<p title="para3">Paragraph 3</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();
		}

	}
}

LocatorByTitle.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 LocatorByTitle {
	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 + "titleDemo.html");

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

			String text = page.getByTitle("para1").textContent();
			System.out.println("Content associated with title 'para1' is : " + text);
			
			text = page.getByTitle("para2").textContent();
			System.out.println("Content associated with title 'para2' is : " + text);
		}
	}
}

Output

Content associated with title 'para1' is : Paragraph 1
Content associated with title 'para2' is : Paragraph 2


Previous                                                 Next                                                 Home

No comments:

Post a Comment