我有一個帶有文本框字段的網頁。靠近它的日曆圖標。當我點擊日曆圖標時,顯示日曆視圖。我認爲它不是一個jquery日曆。任何人都可以提供一個例子來自動化這種類型的日期選擇器。使用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
我試過這個代碼,它可能爲你工作也:
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;
}
}
請使用此代碼從兩個Jquery日曆中選擇日期,如Flight Booking網站。
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();
}
嘗試此,
http://seleniumcapsules.blogspot.com/2012/10/design-of-datepicker.html
- 用作觸發的圖標;
- 單擊圖標時顯示日曆;
- 上一年按鈕(< <),可選;
- 下一年按鈕(>>),可選;
- 上個月按鈕(<);
- 下個月按鈕(>);
- 日按鈕;
- 平日指標;
- 日曆標題,即代表當前月份和當前年份的「2011年9月」。
我認爲會有不同的方式爲不同的日期選擇器格式選擇日期。 對於日期選擇器,您需要從下拉列表中選擇年份和月份,然後選擇/單擊日期, 我編寫了以下代碼。
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);
}
我得到了Selenium Firefox IDE的cssSelector部分。此外,我的日期(csvRow)是(2015-03-31)格式。
希望它有幫助。
通過使用類WebDriverWait來避免'Thread.sleep(1000)'調用會很好。 – Manfred
這個對我來說就像一個魅力,日期選擇器只有上一個和下一個按鈕以及月和年作爲文本。
頁對象如下
[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();
}
這太好了。但是您首先需要使用PageFacotory.InitElements。更多信息,請點擊這裏http://blogs.lessthandot.com/index.php/WebDev/UIDevelopment/automated-web-testing-with-selenium-2/ – Jepzen
這裏有一個整潔的解決方案,您提供的目標日期爲日曆對象。
// 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"));
}
您可以在Selenium中以多種方式處理。
您可以使用直接點擊操作來選擇值
或
你可以寫一般的XPath以匹配所有的壓光值,並點擊具體日期按要求。
我已經寫了詳細的文章。
希望這將有助於
http://learn-automation.com/handle-calender-in-selenium-webdriver/
只是做
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("document.getElementById('id').value='1988-01-01'");
請不要寫純代碼的答案。 – Sumurai8
在這裏,我告訴你從它的官方網站 「https://jqueryui.com/resources/demos/datepicker/default.html」 自動化jQueryUI的壓光我的一部開拓創新的代碼。
複製粘貼代碼,看看它的工作般的魅力:)
投票,如果你喜歡它:) 問候 Avadh戈亞爾
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;
}
}
}
請不要將相同的答案複製粘貼到多個問題上。此外,要求upvotes在這裏違背禮節。 –
此代碼應該正常工作以從日曆中獲取當前日期。
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;
}
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");
}
}
沒有爲保持簡單和愚蠢的,如果日期選擇器來自於一個簡單的HTML5輸入和目標是測試加入到測試的任何事件的說法。考慮到例如:
<input type=date name=mydate />
和一個想要設置一個測試,「指明MyDate」是硬編碼到2017年2月22日,與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')
- 1. 使用Selenium在日期選擇器中自動選擇日期
- 2. Selenium WebDriver CSS選擇器幫助 - 用於選擇日期
- 3. Python&Selenium無法在日期選擇器中選擇日期
- 4. 使用Selenium從Datepicker中選擇日期
- 5. 選擇從jQuery的日期,日期選擇器使用硒的webdriver
- 6. 如何在出生日期的Selenium WebDriver中選擇日期選取器
- 7. 如何使用selenium webdriver從下拉菜單中選擇日期?
- 8. 在jQuery日期選擇器中選擇日期和高亮日期選擇器
- 9. 無法從日期選擇器中的日期選擇器中獲取日期
- 10. 如何在Selenium WebDriver中選擇日期選取器
- 11. 如何在日期選擇器中禁用日期時選擇其他日期選擇器中的日期
- 12. 使用Selenium WebDriver處理日期選擇器
- 13. 如何增加從日期選擇器中選擇的日期?
- 14. 根據日期選擇器中選擇的日期禁用日期選擇器的以前的日期
- 15. 日期選擇器從特定日期
- 16. 選擇js中日期選擇器的可選日期
- 17. 從日曆中選擇日期,然後日期內選擇
- 18. jQuery日期選擇器 - 從第一個日期選擇器中選擇後禁用日期
- 19. 如何啓用從iPhone日曆查看日期選擇器中選擇日期?
- 20. 日期選擇器中隱藏日期
- 21. 在日曆中標記從日期選擇器中選擇的日期
- 22. 設置在日期選擇器中選擇的最短日期
- 23. Python Selenium +日期選擇器問題
- 24. 獲取在日期選擇器中選擇的所有日期
- 25. Android中的日期選擇器日期選擇
- 26. 更改jQuery日期選擇器中的日期選擇其他
- 27. HTML/Angular2日期選擇器禁用以選擇未來日期
- 28. 禁用日期選擇jQuery日期選擇器
- 29. 選擇*從表中選擇兩個日期之間的日期
- 30. 如何使用Jquery日期時間選擇器使用PHP MSQL從日期列中選擇或查詢日期?
我想這一點,這是工作,'driver.findElement(By.id( 「日期按鈕」))點擊();''WebElement StartdateWidget = driver.findElement(By.xpath。 (「xpath of date cell」));''driver.findElement(By.xpath(「xpath of date cell」))。click();''StartdateWidget.findElements(By.tagName(「tr」));' 'StartdateWidget.findElements(By.tagName(「td」));' – Gokul
檢查這個例子 - http://www.tes tautomationguru.com/selenium-webdriver-automating-custom-controls-datepicker/ – vins