Friday, 28 July 2023

Playwright: wait for an element

Using page.waitForSelector() method, we can wait for the selector certain amount of time.

Example

page.waitForSelector("#result", waitForSelectorOptions)

Find the below working application.

 

waitForElement.html

<!DOCTYPE html>
<html>

<head> </head>

<body>


	See the result here

	<script>

		setTimeout(() => {
			const para = document.createElement("p");
			para.setAttribute("id", "result");
			document.body.appendChild(para);
			document.getElementById("result").innerHTML = "<b>Hello World</b>";
		}, 3000);

	</script>

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

	}
}

WaitForAnElement.java

package com.sample.app.miscellaneous;

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

public class WaitForAnElement {

	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("miscellaneous" + File.separator + "waitForElement.html");

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

			WaitForSelectorOptions waitForSelectorOptions = new WaitForSelectorOptions();
			waitForSelectorOptions.setTimeout(5000);

			String resultData = page.waitForSelector("#result", waitForSelectorOptions).textContent();
			System.out.println(resultData);

		}
	}

}

Output

Hello World


 

Previous                                                 Next                                                 Home

No comments:

Post a Comment