Java+selenium 如何操作日历控件

时间:2021-12-03 15:23:05

场景:一般的日期控件都是input标签下弹出来的,如果使用webdriver 去设置日期,

    1. 定位到该input

2. 使用sendKeys 方法

但是,有的日期控件是readonly的 ,比如神州租车 https://mycar.zuche.com/ 。这个时候,没法调用WebElement的sendKeys()

解决方案:使用JS remove readonly attribute,然后sendKeys

Java+selenium  如何操作日历控件

一、Feature 示例

    @E-999
Scenario: E-999:如何定位隐藏元素定位
Then I serach hidden Element 我的订单
Then I select Order date range
|开始日期 | 结束日期 |
|2018-01-01| @today |
Then I verify order information contains 还没租过车?

二、Step 示例:

  @Then("^I select Order date range$")
public void i_select_Order_date_range(DataTable data) throws Exception {
HashMap<String, String> hash = DataTableUtils.toHashMap(data);
String startDate = hash.get("开始日期");
String endDate = Utils.getDate(hash.get("结束日期 "));
pr.selectOrderDateRange(startDate, endDate);
} @Then("^I verify order information contains (.+)$")
public void i_verify_order_information_contains(String info) throws Exception {
pr.verifyOrderInformationContains(info);
}

三、Page 示例:

     /**
* 选择订单日期范围
* @param startDate 开始日期
* @param endDate 结束日期
*/
public void selectOrderDateRange(String startDate, String endDate){
7 String js = "document.getElementById('fromDate').removeAttribute('readonly');";
8 WebDriverUtils.executeJS(""+ js +"", driver);
9 putInValue(By.xpath("//input[@id='fromDate']"), startDate);
String toDate = "document.getElementById('toDate').removeAttribute('readonly');";
WebDriverUtils.executeJS(""+ toDate +"", driver);
putInValue(By.xpath("//input[@id='toDate']"), startDate);
waitFor(By.xpath(".//input[@id='searchBtn']")).click();
} public void verifyOrderInformationContains(String info) {
String actual = waitFor(By.xpath(".//img[contains(@src,'grayben.png')]//following-sibling::*[1]")).getText().trim();
Assert.isContains(actual, info, "验证查询信息");
} }