Friday 28 April 2023

Playwright: Get the first matching element

Locator.first() method return the locator to the first matching element.

 

Example

Locator firstMatchingElement = page.locator(".para").first();

Find the below working application.

 

firstMatchingElement.html

<!DOCTYPE html>

<html>

<head>
	<title>First matching element</title>
</head>

<body>

	<p class="para">Hi there</p>
	<p class="para">I love Java</p>
	<p class="para">Playwright Java library is available for open usage</p>

</html>

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

public class FirstMatchingElement {
	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 + "firstMatchingElement.html");

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

			Locator firstMatchingElement = page.locator(".para").first();
			System.out.println(firstMatchingElement.textContent());

		}
	}
}

Output

Hi there

 

Previous                                                 Next                                                 Home

No comments:

Post a Comment