Merge branch 'page-object-model'

This commit is contained in:
Ramon Caballero 2024-07-27 15:49:18 +01:00
commit 05b089f331
38 changed files with 1278 additions and 541 deletions

25
src/pages/BasePage.java Normal file
View File

@ -0,0 +1,25 @@
package pages;
import org.openqa.selenium.WebDriver;
public abstract class BasePage
{
protected WebDriver driver = null;
protected BasePage(WebDriver driver)
{
this.driver = driver;
}
public void sleep(long millis)
{
try
{
Thread.sleep(millis);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,96 @@
package pages.waits;
import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import pages.BasePage;
public class WaitingStrategiesPage extends BasePage
{
@FindBy(xpath = "//button[contains(text(),'Waiting Strategies')]")
private WebElement accordionItem;
@FindBy(id = "disabled-input-toggle")
private WebElement enableOrDisableButton;
@FindBy(id = "disabled-input")
private WebElement enabledOrDisabledInput;
@FindBy(id = "hidden-input-toggle")
private WebElement showOrHideButton;
@FindBy(id = "hidden-input")
private WebElement shownOrHiddenInput;
@FindBy(id = "add-remove-input-button")
private WebElement addOrRemoveButton;
@FindBy(id = "dynamic-input")
private WebElement dynamicInput;
public WaitingStrategiesPage(WebDriver driver)
{
super(driver);
PageFactory.initElements(this.driver, this);
}
public void clickOnAccordionItem()
{
accordionItem.click();
}
public void clickEnableOrDisableButton()
{
enableOrDisableButton.click();
}
public void setEnabledOrDisabledInput(String text)
{
enabledOrDisabledInput.sendKeys(text);
}
public void clickShowOrHideButton()
{
showOrHideButton.click();
}
public void setShownOrHiddenInput(String text)
{
shownOrHiddenInput.sendKeys(text);
}
public void clickAddOrRemoveButton()
{
addOrRemoveButton.click();
}
public void setDynamicInput(String text)
{
dynamicInput.sendKeys(text);
}
public void waitForEnabledOrDisabledInputToBeClickable(long millis)
{
WebDriverWait wait = new WebDriverWait(driver, Duration.ofMillis(millis));
wait.until(ExpectedConditions.elementToBeClickable(enabledOrDisabledInput));
}
public void waitForShownOrHiddenInputToBeClickable(long millis)
{
WebDriverWait wait = new WebDriverWait(driver, Duration.ofMillis(millis));
wait.until(ExpectedConditions.elementToBeClickable(shownOrHiddenInput));
}
public void waitForDynamicInputToBePresent(long millis)
{
WebDriverWait wait = new WebDriverWait(driver, Duration.ofMillis(millis));
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("dynamic-input")));
}
}

View File

@ -0,0 +1,18 @@
package pages.webdriver;
import org.openqa.selenium.WebDriver;
public class GettingStartedPage
{
private WebDriver driver = null;
public GettingStartedPage(WebDriver driver)
{
this.driver = driver;
}
public String getTitle()
{
return this.driver.getTitle();
}
}

View File

@ -0,0 +1,28 @@
package pages.webelements;
import org.openqa.selenium.Alert;
import org.openqa.selenium.WebDriver;
import pages.BasePage;
public class AlertPanel extends BasePage
{
private Alert alert = null;
public AlertPanel(WebDriver driver)
{
super(driver);
alert = driver.switchTo().alert();
}
public String getText()
{
return alert.getText();
}
public void accept()
{
alert.accept();
driver.switchTo().defaultContent();
}
}

View File

@ -0,0 +1,70 @@
package pages.webelements;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import pages.BasePage;
public class CheckboxesAndRadioButtonsPage extends BasePage
{
@FindBy(xpath = "//button[contains(text(),'Checkboxes and Radio Buttons')]")
private WebElement accordionItem;
@FindBy(xpath = "//div[@id='checkboxes']//input")
private List<WebElement> checkboxes;
@FindBy(xpath = "//div[@id='radiobuttons']//input")
private List<WebElement> radioButtons;
public CheckboxesAndRadioButtonsPage(WebDriver driver)
{
super(driver);
PageFactory.initElements(this.driver, this);
}
public void clickOnAccordionItem()
{
accordionItem.click();
}
public void selectRandomCheckboxes(int howMany)
{
// Collections.shuffle(checkboxes) is not modifying 'checkboxes' !?
// So I shuffle a list of indices instead...
List<Integer> indices = new ArrayList<>();
for (int i = 0; i < checkboxes.size(); i++)
{
indices.add(i);
}
Collections.shuffle(indices);
for (int i = 0; i < howMany; i++)
{
checkboxes.get(indices.get(i)).click();
}
}
public void selectRandomRadioButton()
{
// Collections.shuffle(radioButtons) is not modifying 'radioButtons' !?
// So I shuffle a list of indices instead...
List<Integer> indices = new ArrayList<>();
for (int i = 0; i < radioButtons.size(); i++)
{
indices.add(i);
}
Collections.shuffle(indices);
radioButtons.get(indices.get(0)).click();
}
}

View File

@ -0,0 +1,28 @@
package pages.webelements;
import org.openqa.selenium.Alert;
import org.openqa.selenium.WebDriver;
import pages.BasePage;
public class ConfirmPanel extends BasePage
{
private Alert confirm = null;
public ConfirmPanel(WebDriver driver)
{
super(driver);
confirm = driver.switchTo().alert();
}
public String getText()
{
return confirm.getText();
}
public void dismiss()
{
confirm.dismiss();
driver.switchTo().defaultContent();
}
}

View File

@ -0,0 +1,57 @@
package pages.webelements;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import pages.BasePage;
public class DatePickersPage extends BasePage
{
@FindBy(xpath = "//button[contains(text(),'Date Pickers')]")
private WebElement accordionItem;
@FindBy(id = "html-datepicker")
private WebElement htmlDatePicker;
public DatePickersPage(WebDriver driver)
{
super(driver);
PageFactory.initElements(this.driver, this);
}
public void clickOnAccordionItem()
{
accordionItem.click();
}
public void setDateOnHTMLDatePicker(String inputDateAsString)
{
// JavaScript uses dates in format "yyyy-MM-dd"
// We set the value of the HTML Date Picker input using JavascriptExecutor
// So we need to convert the input date from format "dd-MM-yyyy" into "yyyy-MM-dd"
String inputDateAsStringInJavaScriptFormat = "";
try
{
SimpleDateFormat inputDateFormat = new SimpleDateFormat("dd-MM-yyyy");
Date inputDate = inputDateFormat.parse(inputDateAsString);
SimpleDateFormat outputDateFormat = new SimpleDateFormat("yyyy-MM-dd");
inputDateAsStringInJavaScriptFormat = outputDateFormat.format(inputDate);
}
catch (ParseException e)
{
e.printStackTrace();
}
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].value='" + inputDateAsStringInJavaScriptFormat + "';", htmlDatePicker);
}
}

View File

@ -0,0 +1,31 @@
package pages.webelements;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class Frame
{
@FindBy(id = "frame-button")
private WebElement button;
private WebDriver driver = null;
public Frame(WebDriver driver, WebElement frame)
{
this.driver = driver;
PageFactory.initElements(this.driver, this);
driver.switchTo().frame(frame);
}
public void clickButton()
{
button.click();
}
public void dismiss()
{
driver.switchTo().defaultContent();
}
}

View File

@ -0,0 +1,41 @@
package pages.webelements;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import pages.BasePage;
public class FramesAndWindowsPage extends BasePage
{
@FindBy(xpath = "//button[contains(text(),'Frames and Windows')]")
private WebElement accordionItem;
@FindBy(id = "custom-iframe")
private WebElement frame;
@FindBy(id = "new-window-button")
private WebElement newWindowButton;
public FramesAndWindowsPage(WebDriver driver)
{
super(driver);
PageFactory.initElements(this.driver, this);
}
public void clickOnAccordionItem()
{
accordionItem.click();
}
public WebElement frame()
{
return frame;
}
public void clickNewWindowButton()
{
newWindowButton.click();
}
}

View File

@ -0,0 +1,42 @@
package pages.webelements;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import pages.BasePage;
public class InputRangePage extends BasePage
{
@FindBy(xpath = "//button[contains(text(),'Input Range')]")
private WebElement accordionItem;
@FindBy(id = "range-input")
private WebElement rangeInput;
public InputRangePage(WebDriver driver)
{
super(driver);
PageFactory.initElements(this.driver, this);
}
public void clickOnAccordionItem()
{
accordionItem.click();
}
public void setRangeInputValue(int value)
{
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].value = arguments[1];", rangeInput, value);
}
public void dragAndDropRangeInputBy(int x, int y)
{
Actions move = new Actions(driver);
move.dragAndDropBy(rangeInput, x, y).build().perform();
}
}

View File

@ -0,0 +1,43 @@
package pages.webelements;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import pages.BasePage;
public class InputsWithUIDialogsPage extends BasePage
{
@FindBy(xpath = "//button[contains(text(),'Inputs With UI Dialogs')]")
private WebElement accordionItem;
@FindBy(id = "color-input")
private WebElement colorInput;
@FindBy(id = "file-input")
private WebElement fileInput;
public InputsWithUIDialogsPage(WebDriver driver)
{
super(driver);
PageFactory.initElements(this.driver, this);
}
public void clickOnAccordionItem()
{
accordionItem.click();
}
public void setColor(String color)
{
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].value = arguments[1];", colorInput, color);
}
public void setFile(String text)
{
fileInput.sendKeys(text);
}
}

View File

@ -0,0 +1,49 @@
package pages.webelements;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import pages.BasePage;
public class JavaScriptPopupMessagesPage extends BasePage
{
@FindBy(xpath = "//button[contains(text(),'JavaScript Popup Messages')]")
private WebElement accordionItem;
@FindBy(id = "alert-button")
private WebElement alertButton;
@FindBy(id = "confirm-button")
private WebElement confirmButton;
@FindBy(id = "prompt-button")
private WebElement promptButton;
public JavaScriptPopupMessagesPage(WebDriver driver)
{
super(driver);
PageFactory.initElements(this.driver, this);
}
public void clickOnAccordionItem()
{
accordionItem.click();
}
public void clickAlertButton()
{
alertButton.click();
}
public void clickConfirmButton()
{
confirmButton.click();
}
public void clickPromptButton()
{
promptButton.click();
}
}

View File

@ -0,0 +1,26 @@
package pages.webelements;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
import org.openqa.selenium.support.PageFactory;
import pages.BasePage;
public class ModalDialogPage extends BasePage
{
@FindBy(how = How.ID, using = "form-interactions-modal-close-button")
private WebElement closeButton;
public ModalDialogPage(WebDriver driver)
{
super(driver);
PageFactory.initElements(this.driver, this);
}
public void close()
{
closeButton.click();
}
}

View File

@ -0,0 +1,86 @@
package pages.webelements;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import pages.BasePage;
public class MostCommonInputsPage extends BasePage
{
@FindBy(xpath = "//button[contains(text(),'Most Common Inputs')]")
private WebElement accordionItem;
@FindBy(id = "text-input")
private WebElement textInput;
@FindBy(id = "readonly-input")
private WebElement readonlyInput;
@FindBy(id = "email-input")
private WebElement emailInput;
@FindBy(id = "password-input")
private WebElement passwordInput;
@FindBy(id = "textarea")
private WebElement textarea;
@FindBy(id = "form-interactions-reset-button")
private WebElement resetButton;
@FindBy(id = "form-interactions-submit-button")
private WebElement submitButton;
public MostCommonInputsPage(WebDriver driver)
{
super(driver);
PageFactory.initElements(this.driver, this);
}
public void clickOnAccordionItem()
{
accordionItem.click();
}
public void setText(String text)
{
textInput.sendKeys(text);
}
public void setEmail(String text)
{
emailInput.sendKeys(text);
}
public void setPassword(String text)
{
passwordInput.sendKeys(text);
}
public void setTextarea(String text)
{
textarea.sendKeys(text);
}
public void clearText()
{
textInput.clear();
}
public void reset()
{
resetButton.click();
}
public void submit()
{
submitButton.click();
}
public String getReadonlyValue()
{
return readonlyInput.getAttribute("value");
}
}

View File

@ -0,0 +1,53 @@
package pages.webelements;
import java.util.Set;
import org.openqa.selenium.WebDriver;
import pages.BasePage;
public class NewWindow extends BasePage
{
private String originalWindowHandle;
public NewWindow(WebDriver driver)
{
super(driver);
// Get the handle (or identifier) of the original window:
originalWindowHandle = driver.getWindowHandle();
// Most likely the new window won't finish loading its content before its title is queried by the
// driver, so we sleep the execution a little bit to give it enough time:
sleep(500);
// Get the handles of all the windows (i.e. handle of the original window + handle of the new window):
Set<String> windowHandles = driver.getWindowHandles();
// Figure out the handle of the new window:
String newWindowHandle = "";
for (String windowHandle : windowHandles)
{
if (!originalWindowHandle.contentEquals(windowHandle))
{
newWindowHandle = windowHandle;
break;
}
}
// Switch to the new window:
driver.switchTo().window(newWindowHandle);
}
public String title()
{
return driver.getTitle();
}
public void close()
{
driver.close();
driver.switchTo().window(originalWindowHandle);
}
}

View File

@ -0,0 +1,33 @@
package pages.webelements;
import org.openqa.selenium.Alert;
import org.openqa.selenium.WebDriver;
import pages.BasePage;
public class PromptPanel extends BasePage
{
private Alert prompt = null;
public PromptPanel(WebDriver driver)
{
super(driver);
prompt = driver.switchTo().alert();
}
public void setText(String text)
{
prompt.sendKeys(text);
}
public String getText()
{
return prompt.getText();
}
public void dismiss()
{
prompt.dismiss();
driver.switchTo().defaultContent();
}
}

View File

@ -0,0 +1,58 @@
package pages.webelements;
import java.util.Collections;
import java.util.List;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.Select;
import pages.BasePage;
public class SelectDatalistAndOptionsPage extends BasePage
{
@FindBy(xpath = "//button[contains(text(),'Select, Datalist and Options')]")
private WebElement accordionItem;
@FindBy(id = "select")
private WebElement selectElement;
@FindBy(id = "datalist-input")
private WebElement datalistElement;
Select select = null;
List<WebElement> selectOptions = null;
public SelectDatalistAndOptionsPage(WebDriver driver)
{
super(driver);
PageFactory.initElements(this.driver, this);
select = new Select(selectElement);
// Take the options and remove the 1st option so it cannot be selected:
selectOptions = select.getOptions();
selectOptions.remove(0);
}
public void clickOnAccordionItem()
{
accordionItem.click();
}
public void selectRandomOption()
{
// Shuffle the options to get a random order and select the 1st one:
Collections.shuffle(selectOptions);
select.selectByVisibleText(selectOptions.get(0).getText());
}
public void selectFromDatalist(String text)
{
datalistElement.sendKeys(text);
datalistElement.sendKeys(Keys.RETURN);
}
}

View File

@ -0,0 +1,57 @@
package pages.webelements;
import java.util.List;
import java.util.stream.Collectors;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import pages.BasePage;
public class TablesPage extends BasePage
{
@FindBy(xpath = "//button[contains(text(),'Tables')]")
private WebElement accordionItem;
@FindBy(xpath = ".//table[@id='products-batman']/descendant::*/tr")
private List<WebElement> rows;
List<WebElement> headerRow;
public TablesPage(WebDriver driver)
{
super(driver);
PageFactory.initElements(this.driver, this);
// Take the cells of the 1st row (header row):
headerRow = rows.remove(0).findElements(By.xpath("th"));
}
public void clickOnAccordionItem()
{
accordionItem.click();
}
public String batmanProductsTableHeaderAsString()
{
return headerRow.stream().map(WebElement::getText).collect(Collectors.joining(", "));
}
public String batmanProductsTableRowsAsString()
{
String rowsAsString = "";
for (WebElement row : rows)
{
List<WebElement> cellsInRow = row.findElements(By.xpath("td"));
String rowAsString = cellsInRow.stream().map(WebElement::getText).collect(Collectors.joining(", "));
rowsAsString += rowAsString + '\n';
}
return rowsAsString;
}
}

View File

@ -0,0 +1,61 @@
package tests.waits;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import pages.waits.WaitingStrategiesPage;
public class ExplicitWaitTests
{
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/");
// Instantiate the page model:
WaitingStrategiesPage page = new WaitingStrategiesPage(driver);
// Perform actions on the page:
page.clickOnAccordionItem();
// ======================================================================================== //
//
// DISABLED INPUT
//
// ======================================================================================== //
page.clickEnableOrDisableButton();
page.waitForEnabledOrDisabledInputToBeClickable(1000); // Wait for the JavaScript to enable the input.
page.setEnabledOrDisabledInput("Explicit Wait with disabled elements");
// ======================================================================================== //
//
// HIDDEN INPUT
//
// ======================================================================================== //
page.clickShowOrHideButton();
page.waitForShownOrHiddenInputToBeClickable(1000); // Wait for the JavaScript to show the input.
page.setShownOrHiddenInput("Explicit Wait with hidden elements");
// ======================================================================================== //
//
// DYNAMIC INPUT
//
// ======================================================================================== //
page.clickAddOrRemoveButton();
page.waitForDynamicInputToBePresent(1000);
page.setDynamicInput("Explicit Wait with dynamic elements");
//
// This is commented out so you can actually see what happened in the web page:
// driver.quit();
}
}

View File

@ -1,12 +1,13 @@
package waits; package tests.waits;
import java.time.Duration; import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.firefox.FirefoxDriver;
public class ImplicitWait import pages.waits.WaitingStrategiesPage;
public class ImplicitWaitTests
{ {
private static void sleep(long milliseconds) private static void sleep(long milliseconds)
{ {
@ -25,14 +26,17 @@ public class ImplicitWait
// Specify path to WebDriver: // Specify path to WebDriver:
System.setProperty("webdriver.gecko.driver", "/snap/bin/geckodriver"); System.setProperty("webdriver.gecko.driver", "/snap/bin/geckodriver");
// Launch browser, set implicit waiting time, and navigate to test page: // Launch browser and navigate to test page:
WebDriver driver = new FirefoxDriver(); WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize(); driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(Duration.ofMillis(1000)); driver.manage().timeouts().implicitlyWait(Duration.ofMillis(1000));
driver.get("https://ramoncaballero.dev/sdet/selenium-webdriver/playgrounds/"); driver.get("https://ramoncaballero.dev/sdet/selenium-webdriver/playgrounds/");
// Click on the Waiting Strategies accordion item: // Instantiate the page model:
driver.findElement(By.xpath("//button[contains(text(),'Waiting Strategies')]")).click(); WaitingStrategiesPage page = new WaitingStrategiesPage(driver);
// Perform actions on the page:
page.clickOnAccordionItem();
// ======================================================================================== // // ======================================================================================== //
// //
@ -40,16 +44,14 @@ public class ImplicitWait
// //
// ======================================================================================== // // ======================================================================================== //
// Click on the Enable button that will enable the disabled input: page.clickEnableOrDisableButton();
driver.findElement(By.id("disabled-input-toggle")).click();
// implicitlyWait is used when trying to find an element or elements that are not immediately available. // implicitlyWait is used when trying to find an element or elements that are not immediately available.
// In this case, the disabled input is available (i.e. exists in the DOM), so we sleep the execution // In this case, the disabled input is available (i.e. exists in the DOM), so we sleep the execution
// before continuing: // before continuing:
sleep(1000); sleep(1000);
// Enter some text in the input: page.setEnabledOrDisabledInput("Implicit Wait with disabled elements");
driver.findElement(By.id("disabled-input")).sendKeys("Implicit Wait with disabled elements");
// ======================================================================================== // // ======================================================================================== //
// //
@ -57,16 +59,14 @@ public class ImplicitWait
// //
// ======================================================================================== // // ======================================================================================== //
// Click on the Hide button that will show the hidden input: page.clickShowOrHideButton();
driver.findElement(By.id("hidden-input-toggle")).click();
// implicitlyWait is used when trying to find an element or elements that are not immediately available. // implicitlyWait is used when trying to find an element or elements that are not immediately available.
// In this case, the hidden input is available (i.e. exists in the DOM), so we sleep the execution // In this case, the hidden input is available (i.e. exists in the DOM), so we sleep the execution
// before continuing: // before continuing:
sleep(1000); sleep(1000);
// Enter some text in the input: page.setShownOrHiddenInput("Implicit Wait with hidden elements");
driver.findElement(By.id("hidden-input")).sendKeys("Implicit Wait with hidden elements");
// ======================================================================================== // // ======================================================================================== //
// //
@ -74,14 +74,12 @@ public class ImplicitWait
// //
// ======================================================================================== // // ======================================================================================== //
// Click on the Add button that will add a new input: page.clickAddOrRemoveButton();
driver.findElement(By.id("add-remove-input-button")).click();
// We don't need to sleep here, as the dynamic input doesn't exist in the DOM and implicitlyWait // We don't need to sleep here, as the dynamic input doesn't exist in the DOM and implicitlyWait
// will keep trying for the specified amount of time until the input is available. // will keep trying for the specified amount of time until the input is available.
// Enter some text in the input: page.setDynamicInput("Implicit Wait with dynamic elements");
driver.findElement(By.id("dynamic-input")).sendKeys("Implicit Wait with dynamic elements");
// //

View File

@ -1,9 +1,11 @@
package webdriver; package tests.webdriver;
import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.firefox.FirefoxDriver;
public class GettingStarted import pages.webdriver.GettingStartedPage;
public class GettingStartedTests
{ {
public static void main(String[] args) public static void main(String[] args)
{ {
@ -20,7 +22,8 @@ public class GettingStarted
// 4. Interact with WebElements. // 4. Interact with WebElements.
// When testing on a web page we want to make sure that something in it matches an expected value. // When testing on a web page we want to make sure that something in it matches an expected value.
// For example, this tests that the title of the web page is what we expect: // For example, this tests that the title of the web page is what we expect:
String actual = driver.getTitle(); GettingStartedPage page = new GettingStartedPage(driver);
String actual = page.getTitle();
String expected = "ramoncaballero.dev - Selenium Playground"; String expected = "ramoncaballero.dev - Selenium Playground";
assert actual.equals(expected); assert actual.equals(expected);
@ -29,4 +32,4 @@ public class GettingStarted
// 5. End the session: // 5. End the session:
driver.quit(); driver.quit();
} }
} }

View File

@ -0,0 +1,33 @@
package tests.webelements;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import pages.webelements.CheckboxesAndRadioButtonsPage;
public class CheckboxesAndRadioButtonsTests
{
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/");
// Instantiate the page model:
CheckboxesAndRadioButtonsPage page = new CheckboxesAndRadioButtonsPage(driver);
// Perform actions on the page:
page.clickOnAccordionItem();
page.selectRandomCheckboxes(3);
page.selectRandomRadioButton();
//
// This is commented out so you can actually see what happened in the web page:
// driver.quit();
}
}

View File

@ -0,0 +1,42 @@
package tests.webelements;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import pages.webelements.DatePickersPage;
public class DatePickersTests
{
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/");
// Instantiate the page model:
DatePickersPage page = new DatePickersPage(driver);
// This could be considered our test data:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDate today = LocalDate.now();
String inputDateAsString = formatter.format(today);
// Perform actions on the page:
page.clickOnAccordionItem();
page.setDateOnHTMLDatePicker(inputDateAsString);
//
// This is commented out so you can actually see what happened in the web page:
// driver.quit();
}
}

View File

@ -0,0 +1,42 @@
package tests.webelements;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import pages.webelements.Frame;
import pages.webelements.FramesAndWindowsPage;
import pages.webelements.NewWindow;
public class FramesAndWindowsTests
{
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/");
// Instantiate the page model:
FramesAndWindowsPage page = new FramesAndWindowsPage(driver);
// Perform actions on the page:
page.clickOnAccordionItem();
Frame frame = new Frame(driver, page.frame());
frame.clickButton();
frame.dismiss();
page.clickNewWindowButton();
NewWindow window = new NewWindow(driver);
System.out.println("The title of the new window is: " + window.title());
window.close();
//
// This is commented out so you can actually see what happened in the web page:
// driver.quit();
}
}

View File

@ -0,0 +1,33 @@
package tests.webelements;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import pages.webelements.InputRangePage;
public class InputRangeTests
{
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/");
// Instantiate the page model:
InputRangePage page = new InputRangePage(driver);
// Perform actions on the page:
page.clickOnAccordionItem();
page.setRangeInputValue(0);
page.dragAndDropRangeInputBy(100, 0);
//
// This is commented out so you can actually see what happened in the web page:
// driver.quit();
}
}

View File

@ -0,0 +1,33 @@
package tests.webelements;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import pages.webelements.InputsWithUIDialogsPage;
public class InputsWithUIDialogsTests
{
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/");
// Instantiate the page model:
InputsWithUIDialogsPage page = new InputsWithUIDialogsPage(driver);
// Perform actions on the page:
page.clickOnAccordionItem();
page.setColor("#FF0000");
page.setFile("/home/mon/empty.txt");
//
// This is commented out so you can actually see what happened in the web page:
// driver.quit();
}
}

View File

@ -0,0 +1,49 @@
package tests.webelements;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import pages.webelements.AlertPanel;
import pages.webelements.ConfirmPanel;
import pages.webelements.JavaScriptPopupMessagesPage;
import pages.webelements.PromptPanel;
public class JavaScriptPopupMessagesTests
{
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/");
// Instantiate the page model:
JavaScriptPopupMessagesPage page = new JavaScriptPopupMessagesPage(driver);
// Perform actions on the page:
page.clickOnAccordionItem();
page.clickAlertButton();
AlertPanel alert = new AlertPanel(driver);
System.out.println("Alert text: " + alert.getText());
alert.accept();
page.clickConfirmButton();
ConfirmPanel confirm = new ConfirmPanel(driver);
System.out.println("Confirm text: " + confirm.getText());
confirm.dismiss();
page.clickPromptButton();
PromptPanel prompt = new PromptPanel(driver);
System.out.println("Prompt text: " + prompt.getText());
prompt.dismiss();
//
// This is commented out so you can actually see what happened in the web page:
// driver.quit();
}
}

View File

@ -0,0 +1,54 @@
package tests.webelements;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import pages.webelements.ModalDialogPage;
import pages.webelements.MostCommonInputsPage;
public class MostCommonInputsTests
{
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/");
// Instantiate the page model:
MostCommonInputsPage page = new MostCommonInputsPage(driver);
// Perform actions on the page:
page.clickOnAccordionItem();
page.setText("Selenium WebDriver");
page.setEmail("hello@ramoncaballero.dev");
page.setPassword("YouDontNeedToKnowThis");
page.setTextarea("This is a textarea and I can write inside it.");
page.clearText();
page.setText("Interacting with WebElements");
page.reset();
page.setText("Interacting with WebElements with Selenium WebDriver");
page.setEmail("hello@example.com");
page.setPassword("YouMustNotKnowThis");
page.setTextarea("Let's try to write something again.");
page.submit();
page.sleep(500);
ModalDialogPage modal = new ModalDialogPage(driver);
modal.close();
System.out.println("The read-only input text says '" + page.getReadonlyValue() + "'");
//
// This is commented out so you can actually see what happened in the web page:
// driver.quit();
}
}

View File

@ -0,0 +1,34 @@
package tests.webelements;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import pages.webelements.SelectDatalistAndOptionsPage;
public class SelectDatalistAndOptionsTests
{
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/");
// Instantiate the page model:
SelectDatalistAndOptionsPage page = new SelectDatalistAndOptionsPage(driver);
// Perform actions on the page:
page.clickOnAccordionItem();
page.selectRandomOption();
page.selectFromDatalist("Batman");
//
// This is commented out so you can actually see what happened in the web page:
// driver.quit();
}
}

View File

@ -0,0 +1,33 @@
package tests.webelements;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import pages.webelements.TablesPage;
public class TablesTests
{
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/");
// Instantiate the page model:
TablesPage page = new TablesPage(driver);
// Perform actions on the page:
page.clickOnAccordionItem();
System.out.println("Batman Products Table Header: " + page.batmanProductsTableHeaderAsString());
System.out.println("Batman Products Table Rows: " + page.batmanProductsTableRowsAsString());
//
// This is commented out so you can actually see what happened in the web page:
// driver.quit();
}
}

View File

@ -1,89 +0,0 @@
package waits;
import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class ExplicitWait
{
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 Waiting Strategies accordion item:
driver.findElement(By.xpath("//button[contains(text(),'Waiting Strategies')]")).click();
// ======================================================================================== //
//
// DISABLED INPUT
//
// ======================================================================================== //
// Get a reference to the disabled input (we can do that because the input is in the DOM):
WebElement disabledInput = driver.findElement(By.id("disabled-input"));
// Click on the Enable button that will enable the disabled input:
driver.findElement(By.id("disabled-input-toggle")).click();
// Wait for the JavaScript to enable the input:
WebDriverWait wait = new WebDriverWait(driver, Duration.ofMillis(1000));
wait.until(ExpectedConditions.elementToBeClickable(disabledInput));
// Enter some text in the input:
disabledInput.sendKeys("Explicit Wait with disabled elements");
// ======================================================================================== //
//
// HIDDEN INPUT
//
// ======================================================================================== //
// Get a reference to the hidden input (we can do that because the input is in the DOM):
WebElement hiddenInput = driver.findElement(By.id("hidden-input"));
// Click on the Hide button that will show the hidden input:
driver.findElement(By.id("hidden-input-toggle")).click();
// Wait for the JavaScript to show the input:
wait = new WebDriverWait(driver, Duration.ofMillis(1000));
wait.until(ExpectedConditions.visibilityOf(hiddenInput));
// Enter some text in the input:
hiddenInput.sendKeys("Explicit Wait with hidden elements");
// ======================================================================================== //
//
// DYNAMIC INPUT
//
// ======================================================================================== //
// We cannot get a reference to the dynamic input because it doesn't exist in the DOM yet!
// WebElement dynamicInput = driver.findElement(By.id("dynamic-input"));
// Click on the Add button that will add a new input:
driver.findElement(By.id("add-remove-input-button")).click();
// Wait for the JavaScript to add the input:
wait = new WebDriverWait(driver, Duration.ofMillis(1000));
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("dynamic-input")));
// Enter some text in the input:
driver.findElement(By.id("dynamic-input")).sendKeys("Explicit Wait with dynamic elements");
//
// This is commented out so you can actually see what happened in the web page:
// driver.quit();
}
}

View File

@ -1,48 +0,0 @@
package webelements;
import java.util.Collections;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class CheckboxesAndRadioButtons
{
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 'Checkboxes and Radio Buttons' accordion item:
driver.findElement(By.xpath("//button[contains(text(),'Checkboxes and Radio Buttons')]")).click();
// Get checkboxes and radio buttons by XPath:
List<WebElement> checkboxes = driver.findElements(By.xpath("//div[@id='checkboxes']//input"));
List<WebElement> radioButtons = driver.findElements(By.xpath("//div[@id='radiobuttons']//input"));
// Shuffle the lists to get random order:
Collections.shuffle(checkboxes);
Collections.shuffle(radioButtons);
// Click on the first 3 checkboxes:
for (int i = 0; i < 3; i++)
{
checkboxes.get(i).click();
}
// Click on the first radio button:
radioButtons.get(0).click();
//
// This is commented out so you can actually see what happened in the web page:
// driver.quit();
}
}

View File

@ -1,97 +0,0 @@
package webelements;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class FramesAndWindows
{
private static void sleep(long milliseconds)
{
try
{
Thread.sleep(milliseconds);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
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 'Frames and Windows' accordion item:
driver.findElement(By.xpath("//button[contains(text(),'Frames and Windows')]")).click();
//
// FRAMES
//
// Switch to the iframe:
WebElement frame = driver.findElement(By.id("custom-iframe"));
driver.switchTo().frame(frame);
// Perform the actions we need to do:
driver.findElement(By.id("frame-button")).click();
// Switch back to the default document:
driver.switchTo().defaultContent();
//
// WINDOWS
//
// Get the handle (or identifier) of the original window:
String originalWindowHandle = driver.getWindowHandle();
// Click the button that opens a new window:
driver.findElement(By.id("new-window-button")).click();
// Most likely the new window won't finish loading its content before its title is queried by the
// driver, so we sleep the execution a little bit to give it enough time:
sleep(500);
// Get the handles of all the windows (i.e. handle of the original window + handle of the new window):
Set<String> windowHandles = driver.getWindowHandles();
// Figure out the handle of the new window:
String newWindowHandle = "";
for (String windowHandle : windowHandles)
{
if (!originalWindowHandle.contentEquals(windowHandle))
{
newWindowHandle = windowHandle;
break;
}
}
// Switch to the new window:
driver.switchTo().window(newWindowHandle);
// Perform the actions we need to do:
System.out.println("The title of the new window is: " + driver.getTitle());
// Close the window:
driver.close();
// Switch back to the default document:
driver.switchTo().window(originalWindowHandle);
//
// This is commented out so you can actually see what happened in the web page:
// driver.quit();
}
}

View File

@ -1,37 +0,0 @@
package webelements;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class InputsWithUIDialogs
{
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 'Inputs With UI Dialogs' accordion item:
driver.findElement(By.xpath("//button[contains(text(),'Inputs With UI Dialogs')]")).click();
// Color input:
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("document.getElementById('color-input').value = '#000000';");
// File input:
WebElement fileInput = driver.findElement(By.id("file-input"));
fileInput.sendKeys("/etc/legal");
//
// This is commented out so you can actually see what happened in the web page:
// driver.quit();
}
}

View File

@ -1,65 +0,0 @@
package webelements;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class JavaScriptPopupMessages
{
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 'JavaScript Popup Messages' accordion item:
driver.findElement(By.xpath("//button[contains(text(),'JavaScript Popup Messages')]")).click();
//
// ALERT
//
driver.findElement(By.id("alert-button")).click();
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
alert.accept();
System.out.println("Alert text: " + alertText);
//
// CONFIRM
//
driver.findElement(By.id("confirm-button")).click();
Alert confirm = driver.switchTo().alert();
String confirmText = confirm.getText();
confirm.dismiss();
System.out.println("Confirm text: " + confirmText);
//
// PROMPT
//
driver.findElement(By.id("prompt-button")).click();
Alert prompt = driver.switchTo().alert();
prompt.sendKeys("QA");
String promptText = prompt.getText();
prompt.dismiss();
System.out.println("Prompt text: " + promptText);
//
// This is commented out so you can actually see what happened in the web page:
// driver.quit();
}
}

View File

@ -1,79 +0,0 @@
package webelements;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class MostCommonInputs
{
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 'Most Common Inputs' accordion item:
driver.findElement(By.xpath("//button[contains(text(),'Most Common Inputs')]")).click();
// Text input:
WebElement textInput = driver.findElement(By.id("text-input"));
textInput.sendKeys("Selenium WebDriver");
// Read-only input:
WebElement readonlyInput = driver.findElement(By.id("readonly-input"));
String readonlyText = readonlyInput.getAttribute("value");
System.out.println("The read-only input text says '" + readonlyText + "'");
// Email input:
WebElement emailInput = driver.findElement(By.id("email-input"));
emailInput.sendKeys("hello@ramoncaballero.dev");
// Password input:
WebElement passwordInput = driver.findElement(By.id("password-input"));
passwordInput.sendKeys("YouDontNeedToKnowThis");
// Textarea:
WebElement textarea = driver.findElement(By.id("textarea"));
textarea.sendKeys("This is a textarea and I can write inside it.");
// Clear text input and write something else:
textInput.clear();
textInput.sendKeys("Interacting with WebElements");
// Click Reset button:
driver.findElement(By.id("form-interactions-reset-button")).click();
// Write again on the fields (no need to find the elements as we already have them!):
textInput.sendKeys("Interacting with WebElements with Selenium WebDriver");
emailInput.sendKeys("hello@example.com");
passwordInput.sendKeys("YouMustNotKnowThis");
textarea.sendKeys("Let's try to write something again.");
// Click Submit button:
WebElement submitButton = driver.findElement(By.id("form-interactions-submit-button"));
submitButton.click();
// The modal dialog might take a few milliseconds to appear, so let's wait in a simple way:
try
{
Thread.sleep(500);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
// Close the modal dialog:
driver.findElement(By.id("form-interactions-modal-close-button")).click();
//
// This is commented out so you can actually see what happened in the web page:
// driver.quit();
}
}

View File

@ -1,52 +0,0 @@
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();
}
}

View File

@ -1,52 +0,0 @@
package webelements;
import java.util.List;
import java.util.stream.Collectors;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Tables
{
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 'Tables' accordion item:
driver.findElement(By.xpath("//button[contains(text(),'Tables')]")).click();
//
// Obtain the rows in the 'products-batman' table:
List<WebElement> rows = driver.findElements(By.xpath(".//table[@id='products-batman']/descendant::*/tr"));
// Take the cells of the 1st row (header row):
List<WebElement> headerRow = rows.remove(0).findElements(By.xpath("th"));
// Print the table header cells:
String headerString = headerRow.stream().map(WebElement::getText).collect(Collectors.joining(", "));
System.out.println("Header: " + headerString);
// Print table body cells:
for (WebElement row : rows)
{
List<WebElement> cellsInRow = row.findElements(By.xpath("td"));
String rowString = cellsInRow.stream().map(WebElement::getText).collect(Collectors.joining(", "));
System.out.println("Row: " + rowString);
}
//
// This is commented out so you can actually see what happened in the web page:
// driver.quit();
}
}