テキストボックスフィールドのあるWebページがあります。その近くのカレンダーアイコン。カレンダーアイコンをクリックすると、カレンダービューが表示されます。 jqueryカレンダーではないと思います。このタイプの日付ピッカーを自動化する例を誰かが提供できますか?.
私はこのコードを試しました、それはあなたのためにも働くかもしれません:
DateFormat dateFormat2 = new SimpleDateFormat("dd");
Date date2 = new Date();
String today = dateFormat2.format(date2);
//find the calendar
WebElement dateWidget = driver.findElement(By.id("dp-calendar"));
List<WebElement> columns=dateWidget.findElements(By.tagName("td"));
//comparing the text of cell with today's date and clicking it.
for (WebElement cell : columns)
{
if (cell.getText().equals(today))
{
cell.click();
break;
}
}
Seleniumではさまざまな方法で処理できます。
直接クリック操作を使用して値を選択できます
または
カレンダーのすべての値に一致する一般的なxpathを記述し、要件に従って特定の日付をクリックできます。
私はそれに詳細な投稿を書いています。
それが役に立てば幸い
http://learn-automation.com/handle-calender-in-Selenium-webdriver/
それは実際にはそれがどのようにコード化されているかに依存しますが、このようなものがうまくいくかもしれません:
driver.findElement(By.id("datepicker")).click(); //click field
driver.findElement(By.linkText("Next")).click(); //click next month
driver.findElement(By.linkText("28")).click(); //click day
これは、日付ピッカーに前と次のボタンがあり、テキストとして月と年があるだけの魅力的なものでした。
ページオブジェクトは以下の通りです
[FindsBy(How =How.ClassName, Using = "ui-datepicker-calendar")]
public IWebElement tblCalendar;
[FindsBy(How = How.XPath, Using = "//a[@title=\"Prev\"]")]
public IWebElement btnPrevious;
[FindsBy(How = How.XPath, Using = "//a[@title=\"Next\"]")]
public IWebElement btnNext;
[FindsBy(How = How.ClassName, Using = "ui-datepicker-year")]
public IWebElement lblYear;
[FindsBy(How = How.ClassName, Using = "ui-datepicker-month")]
public IWebElement lblMonth;
public void SelectDateFromDatePicker(string year, string month, string date)
{
while (year != lblYear.Text)
{
if (int.Parse(year) < int.Parse(lblYear.Text))
{
btnPrevious.Clicks();
}
else
{
btnNext.Clicks();
}
}
while (lblMonth.Text != "January")
{
btnPrevious.Clicks();
}
while (month != lblMonth.Text)
{
btnNext.Clicks();
}
IWebElement dateField = PropertiesCollection.driver.FindElement(By.XPath("//a[text()=\""+ date+"\"]"));
dateField.Clicks();
}
このコードは、カレンダーから現在の日付を取得するために適切に機能するはずです。
String today=getCurrentDay(); //function
driver.findElement(By.xpath("here xpath of textbox")).click();
Thread.sleep(5000);
WebElement dateWidgetForm= driver.findElement(By.xpath("here xpath of calender"));
List<WebElement> columns = dateWidgetForm.findElements(By.tagName("td"));
for (WebElement cell: columns) {
String z=cell.getAttribute("class").toString();
if(z.equalsIgnoreCase("day")){
if (cell.getText().equals(today)) {
cell.click();
break;
}
}
private String getCurrentDay() {
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);
return todayStr;
}
これを試して、
http://seleniumcapsules.blogspot.com/2012/10/design-of-datepicker.html
WebDriver driver;
public void launch(){
driver = new FirefoxDriver();
driver.get("http://www.cleartrip.com/");
driver.manage().window().maximize();
System.out.println("The browser launched successfully");
}
public void clickdate(String inputDate){
WebElement ele =driver.findElement(By.id("DepartDate"));
ele.click();
String month = driver.findElement(By.xpath("//div[@class='monthBlock first']/div[1]//span[1]")).getText();
String year = driver.findElement(By.xpath("//div[@class='monthBlock first']/div[1]//span[2]")).getText();
System.out.println("Application month : "+month + " Year :"+year);
int monthNum = getMonthNum(month);
System.out.println("Enum Num : "+monthNum);
String[] parts = inputDate.split("/");
int noOfHits = ((Integer.parseInt(parts[2])-Integer.parseInt(year))*12)+(Integer.parseInt(parts[1])-monthNum);
System.out.println("No OF Hits "+noOfHits);
for(int i=0; i< noOfHits;i++){
driver.findElement(By.className("nextMonth ")).click();
}
List<WebElement> cals=driver.findElements(By.xpath("//div[@class='monthBlock first']//tr"));
System.out.println(cals.size());
for( WebElement daterow : cals){
List<WebElement> datenums = daterow.findElements(By.xpath("//td"));
/*iterating the "td" list*/
for(WebElement date : datenums ){
/* Checking The our input Date(if it match go inside and click*/
if(date.getText().equalsIgnoreCase(parts[0])){
date.click();
break;
}
}
}
}
public int getMonthNum(String month){
for (Month mName : Month.values()) {
if(mName.name().equalsIgnoreCase(month))
return mName.value;
}
return -1;
}
public enum Month{
January(1), February(2), March(3), April(4), May(5), June(6) , July(7), August(8), September(9), October(10), November(11),December(12);
private int value;
private Month(int value) {
this.value = value;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Cleartrip cl=new Cleartrip();
cl.launch();
cl.clickdate("24/11/2015");
}
}
ここでは、jqueryuiカレンダーを自動化するための元のコードを公式サイト " https://jqueryui.com/resources/demos/datepicker/default.html "から示します。
コードをコピーして貼り付け、チャームのように機能することを確認します:)
気に入ったら投票してください:) Avadh Goyal
public class JQueryDatePicker2 {
static int targetDay = 0, targetMonth = 0, targetYear = 0;
static int currenttDate = 0, currenttMonth = 0, currenttYear = 0;
static int jumMonthBy = 0;
static boolean increment = true;
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
String dateToSet = "16/12/2016";
getCurrentDayMonth();
System.out.println(currenttDate);
System.out.println(currenttMonth);
System.out.println(currenttYear);
getTargetDayMonthYear(dateToSet);
System.out.println(targetDay);
System.out.println(targetMonth);
System.out.println(targetYear);
calculateToHowManyMonthToJump();
System.out.println(jumMonthBy);
System.out.println(increment);
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\avadh.goyal\\Desktop\\Selenium-2.52.0\\web driver\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.navigate().to(
"https://jqueryui.com/resources/demos/datepicker/default.html");
driver.manage().window().maximize();
Thread.sleep(3000);
driver.findElement(By.xpath("//*[@id='datepicker']")).click();
for (int i = 0; i < jumMonthBy; i++) {
if (increment) {
driver.findElement(
By.xpath("//*[@id='ui-datepicker-div']/div/a[2]/span"))
.click();
} else {
driver.findElement(
By.xpath("//*[@id='ui-datepicker-div']/div/a[1]/span"))
.click();
}
Thread.sleep(1000);
}
driver.findElement(By.linkText(Integer.toString(targetDay))).click();
}
public static void getCurrentDayMonth() {
Calendar cal = Calendar.getInstance();
currenttDate = cal.get(Calendar.DAY_OF_MONTH);
currenttMonth = cal.get(Calendar.MONTH) + 1;
currenttYear = cal.get(Calendar.YEAR);
}
public static void getTargetDayMonthYear(String dateString) {
int firstIndex = dateString.indexOf("/");
int lastIndex = dateString.lastIndexOf("/");
String day = dateString.substring(0, firstIndex);
targetDay = Integer.parseInt(day);
String month = dateString.substring(firstIndex + 1, lastIndex);
targetMonth = Integer.parseInt(month);
String year = dateString.substring(lastIndex + 1, dateString.length());
targetYear = Integer.parseInt(year);
}
public static void calculateToHowManyMonthToJump() {
if ((targetMonth - currenttMonth) > 0) {
jumMonthBy = targetMonth - currenttMonth;
} else {
jumMonthBy = currenttMonth - targetMonth;
increment = false;
}
}
}
目標日をCalendarオブジェクトとして提供する整然としたソリューションを次に示します。
// Used to translate the Month value of a JQuery calendar to the month value expected by a Calendar.
private static final Map<String,Integer> MONTH_TO_CALENDAR_INDEX = new HashMap<String,Integer>();
static {
MONTH_TO_CALENDAR_INDEX.put("January", 0);
MONTH_TO_CALENDAR_INDEX.put("February",1);
MONTH_TO_CALENDAR_INDEX.put("March",2);
MONTH_TO_CALENDAR_INDEX.put("April",3);
MONTH_TO_CALENDAR_INDEX.put("May",4);
MONTH_TO_CALENDAR_INDEX.put("June",5);
MONTH_TO_CALENDAR_INDEX.put("July",6);
MONTH_TO_CALENDAR_INDEX.put("August",7);
MONTH_TO_CALENDAR_INDEX.put("September",8);
MONTH_TO_CALENDAR_INDEX.put("October",9);
MONTH_TO_CALENDAR_INDEX.put("November",10);
MONTH_TO_CALENDAR_INDEX.put("December",11);
}
// ====================================================================================================
// setCalendarPicker
// ====================================================================================================
/**
* Sets the value of specified web element while assuming the element is a JQuery calendar.
* @param byOpen The By phrase that locates the control that opens the JQuery calendar when clicked.
* @param byPicker The By phrase that locates the JQuery calendar.
* @param targetDate The target date that you want set.
* @throws AssertionError if the method is unable to set the date.
*/
public void setCalendarPicker(By byOpen, By byPicker, Calendar targetDate) {
// Open the JQuery calendar.
WebElement opener = driver.findElement(byOpen);
opener.click();
// Locate the JQuery calendar.
WebElement picker = driver.findElement(byPicker);
// Calculate the target and current year-and-month as an integer where value = year*12+month.
// The difference between the two is the number of months we have to move ahead or backward.
int targetYearMonth = targetDate.get(Calendar.YEAR) * 12 + targetDate.get(Calendar.MONTH);
int currentYearMonth = Integer.valueOf(picker.findElement(By.className("ui-datepicker-year")).getText()) * 12
+ Integer.valueOf(MONTH_TO_CALENDAR_INDEX.get(picker.findElement(By.className("ui-datepicker-month")).getText()));
// Calculate the number of months we need to move the JQuery calendar.
int delta = targetYearMonth - currentYearMonth;
// As a sanity check, let's not allow more than 10 years so that we don't inadvertently spin in a loop for zillions of months.
if (Math.abs(delta) > 120) throw new AssertionError("Target date is more than 10 years away");
// Push the JQuery calendar forward or backward as appropriate.
if (delta > 0) {
while (delta-- > 0) picker.findElement(By.className("ui-icon-circle-triangle-e")).click();
} else if (delta < 0 ){
while (delta++ < 0) picker.findElement(By.className("ui-icon-circle-triangle-w")).click();
}
// Select the day within the month.
String dayOfMonth = String.valueOf(targetDate.get(Calendar.DAY_OF_MONTH));
WebElement tableOfDays = picker.findElement(By.cssSelector("tbody:nth-child(2)"));
for (WebElement we : tableOfDays.findElements(By.tagName("td"))) {
if (dayOfMonth.equals(we.getText())) {
we.click();
// Send a tab to completely leave this control. If the next control the user will access is another CalendarPicker,
// the picker might not get selected properly if we stay on the current control.
opener.sendKeys("\t");
return;
}
}
throw new AssertionError(String.format("Unable to select specified day"));
}
日付ピッカーが単純なhtml5入力からのものであり、目的がテストに追加されたすべてのイベントをテストすることである場合、それを単純で愚かに保つための議論があります。例を考えてみましょう:
<input type=date name=mydate />
'mydate'が02/22/2017にハードコードされているテストを設定したい場合、pythonを使用した解決策は、次のコードを使用することです。します:
def setdate(elem_name, date_str):
elem = driver.find_element_by_name('mydate')
elem.click()
elem.send_keys(Keys.ARROW_LEFT)
elem.send_keys(Keys.ARROW_LEFT)
elem.send_keys(date_str)
setdate('mydate'', '02222017')
別の日付ピッカー形式で日付を選択するには、さまざまな方法があると思います。ドロップダウンから年と月を選択して日付を選択/クリックする必要がある日付ピッカーの場合、次のコードを記述しました。
private void setupDate(WebDriver driver, String csvRow) throws Exception {
String date[] = (csvRow).split("-");
driver.findElement(By.id("flddateanchor")).click();
new Select(driver.findElement(By
.cssSelector("select.ui-datepicker-year")))
.selectByVisibleText(date[0]);
Thread.sleep(1000);
new Select(driver.findElement(By
.cssSelector("select.ui-datepicker-month")))
.selectByVisibleText(date[1]);
Thread.sleep(1000);
driver.findElement(By.linkText(date[2])).click();
Thread.sleep(1000);
}
CssSelectorパーツはSelenium Firefox IDEで入手しました。また、私のDate(csvRow)は(2015-03-31)形式です。
それが役に立てば幸い。
フライト予約サイトのような2つのjqueryカレンダーから日付を選択するには、このコードを使用してください。
Hashtable h=new Hashtable();
h.put("January",0 );
h.put("February",1);
h.put("March",2);
h.put("April",3);
h.put("May",4);
h.put("June",5);
h.put("July",6);
h.put("August",7);
h.put("September",8);
h.put("October",9);
h.put("November",10);
h.put("December",11);
int expMonth;
int expYear;
// Calendar Month and Year
String calMonth = null;
String calYear = null;
boolean dateNotFound;
dateNotFound = true;
expMonth= 5;
expYear = 2014;
while(dateNotFound)
{
calMonth = driver.findElement(By.className("ui-datepicker-month")).getText(); // get the text of month
calYear = driver.findElement(By.className("ui-datepicker-year")).getText();
if(((Integer)h.get(calMonth))+1 == expMonth && (expYear == Integer.parseInt(calYear)))
{
String block="//div[@class='monthBlock first']/table/tbody/tr/td"; // THIS IS FIRST CALENDAR
selectDate(expDate,block);
dateNotFound = false;
}
// parseInt - Converts String to integer and indexof( It will return the index position of String)
else if(((Integer)h.get(calMonth))+1 < expMonth && (expYear == Integer.parseInt(calYear)) || expYear > Integer.parseInt(calYear))
{
String block="//div[@class='monthBlock last']/table/tbody/tr/td"; // THIS IS SECOND CALENDAR
selectDate(expDate,block); // PASSING DATE AND CALENDAR
dateNotFound = false; // Otherwise it will rotate continuously
}
else if((Integer)h.get(calMonth)+1 > expMonth && (expYear == Integer.parseInt(calYear)) || expYear < Integer.parseInt(calYear))
{
System.out.println(" Please enter the date greater than Current date");
dateNotFound = false;
}
}
}
//Thread.sleep(3000);
public static void selectDate(String date,String block) throws IOException
{
String monthblock=block;
List<WebElement> dateWidget = driver.findElements(By.xpath(monthblock));
for (WebElement cell: dateWidget)
{
//Selects Date
if (cell.getText().equals(date))
{
cell.findElement(By.linkText(date)).click();
break;
}
}
//Doubt : How to verify the expected results and how to sort the program
driver.findElement(By.id("SearchBtn")).submit();
//driver.quit();
}