PageObjectModel/src/webelements/SelectDatalistAndOptions.java

53 lines
1.7 KiB
Java

package webelements;
import java.util.Collections;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
public class SelectDatalistAndOptions
{
public static void main(String[] args)
{
// Specify path to WebDriver:
System.setProperty("webdriver.gecko.driver", "/snap/bin/geckodriver");
// Launch browser and navigate to test page:
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("https://ramoncaballero.dev/sdet/selenium-webdriver/playgrounds/");
// Click on the 'Select, Datalist and Options' accordion item:
driver.findElement(By.xpath("//button[contains(text(),'Select, Datalist and Options')]")).click();
// Initialize a Select object with the HTML select:
WebElement selectElement = driver.findElement(By.id("select"));
Select select = new Select(selectElement);
// Take the options and remove the 1st option
// (that option cannot be selected as it disappears when another one is selected):
List<WebElement> selectOptions = select.getOptions();
selectOptions.remove(0);
// Shuffle the options to get a random order and select the 1st one:
Collections.shuffle(selectOptions);
select.selectByVisibleText(selectOptions.get(0).getText());
//
WebElement datalistElement = driver.findElement(By.id("datalist-input"));
datalistElement.sendKeys("Batman");
datalistElement.sendKeys(Keys.RETURN);
//
// This is commented out so you can actually see what happened in the web page:
// driver.quit();
}
}