page.frameLocator() method return a frame locator that will enter the iframe and allow selecting elements in that iframe.
Example
FrameLocator frameLocator = page.frameLocator("#javaTutorial");
System.out.println("title : " + frameLocator.locator("title").textContent());
Find the below working application.
iframe.html
<!DOCTYPE html>
<html>
<head>
<title>iframe demo</title>
</head>
<body>
<h1>iframe demo</h1>
<iframe src="https://self-learning-java-tutorial.blogspot.com/2018/08/spring-framework.html"
id="springFrameworkTutorial" width="800" height="500"></iframe>
<iframe src="https://self-learning-java-tutorial.blogspot.com/2016/05/java-home-page.html" id="javaTutorial"
width="800" height="500">
</iframe>
</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();
}
}
}
IFrameDemo.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.FrameLocator;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.Playwright;
import com.sample.app.util.FileUtil;
public class IFrameDemo {
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 + "iframe.html");
Page page = browser.newPage();
page.setContent(content);
FrameLocator frameLocator = page.frameLocator("#javaTutorial");
System.out.println("title : " + frameLocator.locator("title").textContent());
frameLocator = page.frameLocator("#springFrameworkTutorial");
System.out.println("title : " + frameLocator.locator("title").textContent());
}
}
}
Output
title : Programming for beginners: Java Home page title : Programming for beginners: Spring Framework
No comments:
Post a Comment