Vừa rồi tôi đã mất khá nhiều thời gian tìm hiểu về phần chọn ngày trong Date Picker nên muốn chia sẻ lại code đang dùng để giúp các bạn tiết kiệm thời gian nếu có dịp làm đến nó.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 |
package com.example.tests; import java.util.Arrays; import java.util.List; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.junit.After; import org.junit.Before; import org.junit.Test; public class DatePicker { WebDriver driver; WebElement dateWidget; List<WebElement> rows; List<WebElement> columns; List<String> list = Arrays.asList("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"); int expMonth; int expYear; String expDate = null; // Calendar Month and Year. String calMonth = null; String calYear = null; boolean dateNotFound; @Before public void start() { System.setProperty("webdriver.chrome.driver", "E:/SB-Selenium/libs/chromedriver_win32/chromedriver.exe"); driver = new ChromeDriver(); } @Test public void testJQueryDatePicket() throws InterruptedException { driver.get("http://jqueryui.com/datepicker/"); driver.switchTo().frame(0); driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); driver.findElement(By.id("datepicker")).click(); dateNotFound = true; // Set the date here. Eg: 11/01/2016. expMonth = 1; expYear = 2016; expDate = "11"; while (dateNotFound) { calMonth = driver.findElement(By.className("ui-datepicker-month")).getText(); calYear = driver.findElement(By.className("ui-datepicker-year")).getText(); if(list.indexOf(calMonth)+1 == expMonth && (expYear == Integer.parseInt(calYear))) { selectDate(expDate); dateNotFound = false; } else if(list.indexOf(calMonth)+1 < expMonth && (expYear == Integer.parseInt(calYear)) || expYear > Integer.parseInt(calYear)) { driver.findElement(By.xpath(".//*[@id='ui-datepicker-div']/div/a[2]/span")).click(); } else if(list.indexOf(calMonth)+1 > expMonth && (expYear == Integer.parseInt(calYear)) || expYear < Integer.parseInt(calYear)) { driver.findElement(By.xpath(".//*[@id='ui-datepicker-div']/div/a[1]/span")).click(); } } Thread.sleep(3000); } public void selectDate(String date) { dateWidget = driver.findElement(By.id("ui-datepicker-div")); rows = dateWidget.findElements(By.tagName("tr")); columns = dateWidget.findElements(By.tagName("td")); for (WebElement cell : columns) { if (cell.getText().equals(date)) { cell.findElement(By.linkText(date)).click(); break; } } } @After public void tearDown() throws Exception { try { driver.close(); Thread.sleep(3000); } catch (Exception b) { b.getMessage(); } } } |
One Comment