【问题标题】:how can I select two dates today and tomorrow from calendar of booking website using selenium webdriver如何使用 selenium webdriver 从预订网站的日历中选择今天和明天的两个日期
【发布时间】:2018-12-01 05:28:20
【问题描述】:

我尝试使用下面的代码来检测签到按钮,但我不知道如何选择上图所示的日期。

public class Hotel_Search {

    void search(WebDriver driver) {
        // find destination WebElement des = driver.findElement(By.name("ss"));
        // fill destination des.sendKeys("Ain Sokhna");
        // select checkin button WebElement Checkinhbutton = driver.findElement(By.xpath("html/body/div[3]/div/div/div[2]/form/div1/div[2]/div/div[2]/div/div/div/div1/div/button")); Checkinhbutton.click(); //call select date of today method SelectDateOfToday(driver.findElement(By.xpath("html/body/div[3]/div/div/div[2]/form/div1/div[2]/div/div[2]/div/div/div/div[2]/div[2]/div[3]/div/div/div1/table/thead/tr1/th"))); //find search button WebElement searchbutton = driver.findElement(By.xpath("html/body/div[3]/div/div/div[2]/form/div1/div[4]/div[2]/button"));
        // searchbutton.click(); }
        // public void SelectDateOfToday(WebElement Calender_Xpath) {

        String today = getCurrentDay();
        List<WebElement> columns = Calender_Xpath.findElements(By.tagName("td"));
        for (WebElement cell : columns) {
            //If you want to click 18th Date if (cell.getText().equals("18")) {
            // Select Today's Date
            if (cell.getText().equals(today)) {
                cell.click();
                break;
            }
        }
    }

    private String getCurrentDay() {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate localDate = LocalDate.now();
        String date = dtf.format(localDate);
        return date;

    }
}

【问题讨论】:

  • 推送您的代码和 HTML(或 URL)。这不是为您编写代码的服务。

标签: selenium selenium-webdriver automated-tests


【解决方案1】:

这是另一种解决方案

@Test
public void calendarSelector() throws Exception {
    driver.get("https://www.booking.com/");
    WebDriverWait wait = new WebDriverWait(driver, 15, 100);

    //Define locators in advance (Really should move this stuff into a page object)
    By checkInLocator = By.xpath("//div[contains(@class, 'b-datepicker')][@data-mode='checkin']");
    By calendarLocator = By.cssSelector(".bui-calendar__content");

    //Wait until checkIn element is displayed and then click on it
    wait.until(ExpectedConditions.visibilityOfElementLocated(checkInLocator)).click();
    //Wait until calendar is displayed
    wait.until(ExpectedConditions.visibilityOfElementLocated(calendarLocator));

    //Work out today and tomorrow
    LocalDate today = LocalDate.now();
    LocalDate tomorrow = today.plusDays(1L);

    //Use selectDate method to click on the relevant dates
    selectDate(driver, today);
    selectDate(driver, tomorrow);
}

private void selectDate(WebDriver driver, LocalDate date) {
    //Looking at the markup the attribute data-date is formatted as an ISO_LOCAL_DATE
    DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE;
    WebDriverWait wait = new WebDriverWait(driver, 15, 100);
    //Programmatically generate dateLocator based on date passed in
    By dateLocator = By.xpath(String.format("//td[@data-date='%s']", formatter.format(date)));
    //Wait for date element to be visible, then click on it
    wait.until(ExpectedConditions.visibilityOfElementLocated(dateLocator)).click();
}

如果您想搜索未在日历小部件的初始打开时显示的日期,则选择日期方法需要稍微复杂一些,您需要计算出显示的日期,与您想要的日期进行比较然后适当地单击月份导航按钮,但是对于当前方案,您不需要该附加功能。

【讨论】:

    【解决方案2】:

    正如我从您的问题中了解到的,您正试图与https://www.booking.com/ 互动。为了能够选择日期,您可以尝试以下操作:

    import com.google.common.base.Function;
    import org.openqa.selenium.By;
    import org.openqa.selenium.JavascriptExecutor;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.chrome.ChromeDriver;
    import org.openqa.selenium.support.ui.WebDriverWait;
    
    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    import java.util.List;
    import java.util.Locale;
    
    public class BookingTest {
      public static void main(String[] args) throws InterruptedException {
        // Create a new instance of the Firefox driver
        // Notice that the remainder of the code relies on the interface,
        // not the implementation.
        final WebDriver driver = new ChromeDriver();
    
        // And now use this to visit Google
        driver.get("https://www.booking.com/");
        // wait until page will load completely
        new WebDriverWait(driver, 10).until(
            (Function<? super WebDriver, Boolean>) webDriver -> ((JavascriptExecutor) driver)
                .executeScript("return document.readyState").equals("complete"));
    
        // open calendar
        // note sometimes the xpath to the clendar button gets changed, therefore is the 'if' statement here
        List<WebElement> openCalButton = driver.findElements(By.xpath("//button[@aria-label= 'Open calendar']"));
        if (openCalButton.size() < 1){
          openCalButton = driver.findElements(By.xpath("//span[@class= 'sb-date-field__icon sb-date-field__icon-btn bk-svg-wrapper calendar-restructure-sb']"));
        }
        openCalButton.get(0).click();
    
        // store month and year
        Calendar cal=Calendar.getInstance();
        SimpleDateFormat month_date = new SimpleDateFormat("MMMM", Locale.US);
        String month_name = month_date.format(cal.getTime());
        String year = Calendar.getInstance().get(Calendar.YEAR) + "";
        String monthYear = month_name + " " + year;
    
        // store day
        String day = Calendar.getInstance().get(Calendar.DAY_OF_MONTH) + "";
    
        // find date
        WebElement date =  driver.findElements(By.xpath("//th[contains(.,'"
            + monthYear + "')]/parent::*/parent::*/parent::*/tbody/tr/td/span[@class = 'c2-day-inner'][contains(.,'"
            + day + "')]")).get(0);
        date.click();
    
        // this pause is only to prevent to exit the code immediately, if you want to see yhe result before page closes
        Thread.sleep(3000);
        driver.quit();
      }
    }
    

    输出:

    【讨论】:

    • 我尝试了代码,但在这一行中出现此错误“表达式的类型必须是数组类型,但它解析为 List”--- WebElement date = driver.findElements (By.xpath("//th[contains(.,'" + monthYear + "')]/parent::*/parent::*/parent::*/tbody/tr/td/span[@class= 'c2-day-inner'][contains(.,'" + day + "')]"))[1]; date.click();
    • 嗨!我添加了一个工作示例,请尝试一下。注意:对于此代码,您需要 Java 8。请告诉我它是否适合您
    • 那么,您选择日期的问题解决了吗?我的代码对你有用吗?
    猜你喜欢
    • 2021-01-20
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 2014-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多