如何在 Selenium WebDriver 中选择日期选择器?
我们可以在 Selenium 中选择日期选择器。处理日历控件有些困难,因为日期、月份和年的选择可以通过不同的 UI 来表示。
有时它们由下拉框或由前进和后退控件表示。我们选择如下所示的日期选择器。
起始日期 −
结束日期 −
示例
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; import org.openqa.selenium.support.ui.Select; public class DatePicker{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe"); WebDriver driver = new ChromeDriver(); String frdate = "20"; String todate = "26"; driver.get("https://jqueryui.jqueryjs.cn/datepicker/#date−range"); // wait of 4 seconds driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS); // maximize browser driver.manage().window().maximize(); // identify frame and switch to it WebElement e = driver.findElement(By.xpath("//*[@id='content']/iframe")); driver.switchTo().frame(e); // choose from date driver.findElement(By.xpath("//input[@id='from']")).click(); Thread.sleep(1000); // choose month from dropdown WebElement m = driver .findElement(By.xpath("//div/select[@class='ui− datepicker−month']")); Select s = new Select(m); s.selectByVisibleText("Jan"); Thread.sleep(1000); // select day driver.findElement(By.xpath("//td[not(contains(@class,'ui−datepicker− month'))]/a[text()='"+frdate+"']")).click(); Thread.sleep(1000); // choose to date driver.findElement(By.xpath("//input[@id='to']")).click(); Thread.sleep(1000); // choose month from dropdown WebElement n = driver .findElement(By.xpath("//div/select[@class='ui− datepicker−month']")); Select sel = new Select(n); sel.selectByVisibleText("Feb"); Thread.sleep(1000); // select day driver.findElement(By.xpath("//td[not(contains(@class,'ui−datepicker− month'))]/a[text()='"+todate+"']")).click(); Thread.sleep(1000); } }
输出
广告