如何在 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.com/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); } }
輸出
廣告