Using 'page.selectOption()' method, we can select an option from the drop down list.
Example
page.selectOption("select#favoriteColor", "yellow");
Find the below working application.
selectOption.html
<html>
<body>
<h1>Simple select demo</h1>
<form onsubmit="return false;">
<label for="colors">Choose a color:</label>
<select name="colors" id="favoriteColor">
<option value="red">Red</option>
<option value="green">Green</option>
<option value="yellow">Yellow</option>
<option value="blue">blue</option>
</select>
<br><br>
<input type="submit" value="Submit" onclick="display()">
</form>
<p id="result"></p>
<script>
function display() {
let e = document.getElementById('favoriteColor');
var selectedColor = e.options[e.selectedIndex].text;
result.innerHTML = `<b>Selected color: <br />${selectedColor}</b>`
}
</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();
}
}
}
SelectOption.java
package selectOption;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
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 SelectOption {
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(1000));
final String content = FileUtil.resourceAsString("miscellaneous" + File.separator + "selectOption.html");
Page page = browser.newPage();
page.setContent(content);
page.selectOption("select#favoriteColor", "yellow");
page.locator("input[type=\"submit\"]").click();
String textContent = page.locator("id=result").textContent();
System.out.println(textContent);
TimeUnit.SECONDS.sleep(3);
}
}
}
Output
Selected color: Yellow
No comments:
Post a Comment