我正在使用selenium Webdriver(Java)学习自动化,我想在this webpage.上练习一些东西
我无法使用日期选择器选择特定日期。这是我的代码试图这样做:
String parentWindow = driver.getWindowHandle();
String subWindow = null;
driver.findElement(By.xpath(".//*[@id='ns_7_CO19VHUC6VU280AQ4LUKRK0IR7_fmOutboundDateDisplay']")).click(); //Clicking on datepicker icon
// Change to a new window
String parentWindow = driver.getWindowHandle();
String subWindow = null;
Set<String> handles = driver.getWindowHandles(); // get all window handles
Iterator<String> iterator1 = handles.iterator();
while (iterator.hasNext()){
subWindow = iterator.next();
}
driver.switchTo().window(subWindow);
driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
driver.findElement(By.xpath("//*[@class='calendarBodyContainer']/tr[2]/td[3]/span")).click(); //Departure Date- 10Feb/2015
driver.findElement(By.xpath(".//*[@class='calendarBodyContainer']/tr[4]/td[4]/span")).click(); //Arrival Dtae- 25 Feb/2015
driver.switchTo().window(parentWindow);
但是,我收到以下错误:
线程“main”中的异常org.openqa.selenium.NoSuchElementException:无法定位元素:{“method”:“xpath”,“selector”:“// * [@ class ='calendarBodyContainer'] / tr [ 2] / TD [3] /跨度“} 命令持续时间或超时:3.12秒
请帮忙。
答案 0 :(得分:2)
问题是您将日历窗口小部件误认为是新窗口并相应地自动化,导致找不到该元素,正确地怀疑 @alecxe
请尝试以下代码,看看它是否适合您。
WebDriver driver=new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
//Navigating to the site
driver.get("http://www.lufthansa.com/online/portal/lh/us/homepage");
//Clicking on the Departing field to select date
driver.findElement(By.id("ns_7_CO19VHUC6VU280AQ4LUKRK0IR7_fmOutboundDateDisplay")).click();
//Selecting Feb 10, 2015 for departure date
driver.findElement(By.xpath("//td[@dojoattachpoint = 'calRightNode']//span[.='10']")).click();
//Waiting for the return calendar with "Return" as the header to appear
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@dojoattachpoint='calHeadlineNode' and contains(text(),'Return')]")));
//Selecting Feb 26, 2015 for returning date
driver.findElement(By.xpath("//td[@dojoattachpoint = 'calLeftNode']//span[.='26']")).click();
注意:我已添加explicit wait,等待&#34;返回日历窗口小部件中的返回文字&#34;因为它与离开/出站日历重叠,因此硒需要一点时间来检测DOM的变化。
答案 1 :(得分:1)
我会尝试两件事:
尝试以下xpath
(依赖table
元素和span
的文字):
//table[@class='calendarContainer'][1]//span[. = '09']
explicitly waiting for an element:
WebDriverWait wait = new WebDriverWait(webDriver, 5);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//table[@class='calendarContainer'][1]//span[. = '09']"))).click();
我也不确定在这里切换窗口的必要性。