5.14. Date picker

Date picker là một dạng đối tượng khá phổ biến thường xuất hiện trên các trang web về mua vé hoặc các ứng dụng về lịch. Thông qua ví dụ dưới đây cho mọi người một cách tiếp cận cụ thể.

public class DatePicker {
    WebDriver driver;
    WebDriverWait wait;


    @BeforeClass
    void setUp() {
        driver = new ChromeDriver();
        wait = new WebDriverWait(driver, 10);
    }

    @Test
    void ticketPage(){
        driver.get("https://www.vietnamairlines.com/vn/en/home");
        //Accept cookie footer pop up
        wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.id("cookie-agree"))).get(0).click();
        // select depart date
        driver.findElement(By.id("roundtrip-date-depart")).click();
        WebElement dateWidgetFrom = wait.until(
                ExpectedConditions.visibilityOfAllElementsLocatedBy(By.className("ui-datepicker-calendar"))).get(0);

        // This are the columns of the from date picker table
        List<WebElement> columns = dateWidgetFrom.findElements(By.tagName("td"));
        DateUtils.clickGivenDay(columns, DateUtils.getCurrentDay());
        //close date pickper
        driver.findElement(By.className("ui-datepicker-close")).click();

    }

    @AfterClass
    void tearDown() {
        driver.quit();
    }

}

Thư viện DateUtils

import org.openqa.selenium.WebElement;

import java.time.LocalDate;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;

public class DateUtils {
    //Get The Current Day
    public static String getCurrentDay() {
        //Create a Calendar Object
        Calendar calendar = Calendar.getInstance(TimeZone.getDefault());

        //Get Current Day as a number
        int todayInt = calendar.get(Calendar.DAY_OF_MONTH);
        System.out.println("Today Int: " + todayInt + "\n");

        //Integer to String Conversion
        String todayStr = Integer.toString(todayInt);
        System.out.println("Today Str: " + todayStr + "\n");

        return todayStr;
    }

    //Get The Current Day plus days. You can change this method based on your needs.
    public static String getCurrentDayPlus(int days) {
        LocalDate currentDate = LocalDate.now();

        int dayOfWeekPlus = currentDate.getDayOfWeek().plus(days).getValue();
        return Integer.toString(dayOfWeekPlus);
    }

    //Click to given day
    public static void clickGivenDay(List<WebElement> elementList, String day) {
        //DatePicker is a table. Thus we can navigate to each cell
        //and if a cell matches with the current date then we will click it.
        /**Functional JAVA version of this method.*/
        elementList.stream()
                .filter(element -> element.getText().contains(day))
                .findFirst()
                .ifPresent(WebElement::click);

    }
}

Last updated

Was this helpful?