Selenium(Java)——日期控件定位及操作

以12306网站的日期控件为例,定位该控件并输入自定义日期。

思路:

1. 查看元素,发现日期输入框有readonly属性;

2. 利用js去掉readonly属性,将控件变为可编辑状态;

3. 清空输入框中数据(如果有),输入自定义日期。

代码:

package com.ceres.demos;

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.chrome.ChromeOptions;

public class HandleDatePicker {

	public static void main(String[] args) throws InterruptedException {
		ChromeOptions options = new ChromeOptions();
		options.addArguments("disable-infobars");
		WebDriver driver = new ChromeDriver(options);
		driver.manage().window().maximize();
		driver.get("https://www.12306.cn/index/");
		Thread.sleep(2000);
		/*
		 * 使用js定位日期控件,并去掉控件的readonly属性;
		 */
		String js = "document.getElementById('train_date').removeAttribute('readonly');";
		((JavascriptExecutor) driver).executeScript(js);
		/*
		 * 清空日期控件中的值,并输入目标日期值;
		 */
		WebElement datePicker = driver.findElement(By.id("train_date"));
		datePicker.clear();
		Thread.sleep(1000);
		datePicker.sendKeys("2019-03-22");
	}

}

效果:

发布了37 篇原创文章 · 获赞 47 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/u013378642/article/details/88727567