未选择日历元素 - Selenium Webdriver

Calendar Element not getting selected- Selenium Webdriver

我正在使用 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);

但是,我收到以下错误:

Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"xpath","selector":"//*[@class='calendarBodyContainer']/tr[2]/td[3]/span"} Command duration or timeout: 3.12 seconds

请帮忙。

我会尝试两件事:

  • 尝试以下 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();
    

我也不确定切换windows的必要性。

问题是您将 日历小部件误认为是新的 window 并相应地自动化了 ,这导致找不到该元素, 正确怀疑@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 以等待 "Return Calendar widget" 中的 Return 文本,因为它与 Departing/Outbound Calendar,因此 selenium 需要一点时间来检测 DOM.

中的变化