一般的日期控件都是input標(biāo)簽下彈出來(lái)的,如果使用webdriver 去設(shè)置日期,
1. 定位到該input
2. 使用sendKeys 方法
比如:
但是,有的日期控件是readonly的
比如12306的這個(gè)
<input id="train_date" class="inp-txt" type="text" value="2015-03-15" name="back_train_date" autocomplete="off" maxlength="10" readonly="readonly" disabled="disabled">
這個(gè)時(shí)候,沒(méi)法調(diào)用WebElement的sendKeys()
方案一:使用JS remove readonly attribute,然后sendKeys
還是以萬(wàn)惡的12306為例:
使用出發(fā)日期,將input標(biāo)簽的readonly熟悉去掉
JavascriptExecutor removeAttribute = (JavascriptExecutor)driver;
//remove readonly attribute
removeAttribute.executeScript("var setDate=document.getElementById("train_date");setDate.removeAttribute('readonly');") ;
方案二:采用click直接選擇日期,日期控件是一個(gè)iframe,首先switch iframe,之后找到想要設(shè)置的日期button click,然后switch出來(lái)
WebElement dayElement=driver.findElement(By.xpath("//span[@id='from_imageClick']"));
dayElement.click();
// WebElement frameElement=driver.findElement(By.xpath("//iframe[@border='0']"));
driver.switchTo().frame(1);
driver.findElement(By.xpath("//tr/td[@onclick='day_Click(2015,2,21);']")).click();
driver.switchTo().defaultContent();
具體代碼如下:
WebDriver driver=DriverFactory.getFirefoxDriver();
driver.get("https://kyfw.12306.cn/otn/");
driver.manage().window().maximize();
driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);
WebElement fromStation=driver.findElement(By.xpath("//input[@id='fromStationText']"));
fromStation.click();
fromStation.sendKeys("鄭州");
WebElement choseFrom =driver.findElement(By.xpath("//div/span[@class='ralign' and text()='鄭州']"));
choseFrom.click();
WebElement toStation=driver.findElement(By.xpath("//input[@id='toStationText']"));
toStation.click();
toStation.sendKeys("上海");
WebElement choseElement =driver.findElement(By.xpath("//div/span[@class='ralign' and text()='上海']"));
choseElement.click();
JavascriptExecutor removeAttribute = (JavascriptExecutor)driver;
//remove readonly attribute
removeAttribute.executeScript("var setDate=document.getElementById("train_date");setDate.removeAttribute('readonly');") ;
WebElement setDatElement=driver.findElement(By.xpath("//input[@id='train_date']"));
setDatElement.clear();
setDatElement.sendKeys("2015-02-18");
WebElement dayElement=driver.findElement(By.xpath("//span[@id='from_imageClick']"));
dayElement.click();
// WebElement frameElement=driver.findElement(By.xpath("//iframe[@border='0']"));
driver.switchTo().frame(1);
driver.findElement(By.xpath("//tr/td[@onclick='day_Click(2015,2,21);']")).click();
driver.switchTo().defaultContent();
WebElement searchElement=driver.findElement(By.xpath("//div/a[@id='a_search_ticket']"));
searchElement.click();