Reputation: 61
Im trying to open the calendar and click the month. I can manage to open up the calendar but my xpath for the calendar isnt being recognized. I validated that my xpath works in the chrome console but its only able to validate it once the calendar is opened. Can someone please help me out? Thanks!
`import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class CalendarExample {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver","C:\\Program Files\\Java\\Selenium\\Drivers\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.path2usa.com/travel-companions");
List<WebElement> dates = driver.findElements(By.className("day"));
String text = "";
//select August 22 from calendar
//step 1: open the calendar
driver.findElement(By.xpath("//input[@id='travel_date']")).click();
//step 2: click the month
driver.findElement(By.xpath("//body/div[4]/div[@class='datepicker-days']/table//th[@class='datepicker-switch']")).click();
}
}
Upvotes: 1
Views: 2909
Reputation: 3894
In selenium, an element object is returned only when the element is visible in the browser. On the other hand, if the element is not visible, Selenium.ElementNotVisibleException is returned. So, looking at the issue you shared, it is possible that the calendar elements are being created only when its open, so at the time you are trying to click on calendar, you have to ensure the calendar is open. Only then, the element will be returned.
PS: One suggestion of what kind of XPath you should use, Please refer: https://stackoverflow.com/a/49497529/1262248
Upvotes: 1
Reputation: 25
The element is not visible when you are trying to click it.
Declare this at the start of your class:
WebDriverWait wait = new WebDriverWait(driver, 20);
Then, before you click the element insert this:
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//body/div[4]/div[@class='datepicker-days']/table//th[@class='datepicker-switch']")));
Hope this helps.
Upvotes: 0
Reputation: 2174
You experience your error because you are trying to access an element before it is available in DOM
.
So just first open calendar and after that access element with class "day".
No need to change your xpath
.
//open calendar
driver.findElement(By.xpath("//input[@id='travel_date']")).click();
//access element with class "day"
List<WebElement> dates = driver.findElements(By.className("day"));
Upvotes: 0