Skip to content
Advertisement

Cannot write dynamic xpath for element in page

This is the Url: http://automationpractice.com/index.php

I want to select “casual dresses”, but when I tried the “Women” WebElement is selected instead.

How can I write the dyanmic xpath to select “casual dresses”?

Advertisement

Answer

You have to wait until page is loaded, then hover over Women title, the wait until the menu is open and then click on the Casual Dress item.
It’s best practice to keep variables in the top of class, not inside the code hardcoded.
Try this:

//Define expected conditions explicitly wait
WebDriverWait wait = new WebDriverWait(driver, 30);
//Define Actions object instance
Actions action = new Actions(driver);
//define locators
String womenTitleXpath = "//a[@title='Women']";
String up = "/..";
String womenCasualDressXpath = womenTitleXpath + up + "//a[@title='Casual Dresses']";
//Wait until the element is visible
wait.until(ExpectedConditions.visibilityOf(By.xpath(womenTitleXpath)));
WebElelemnt womenTitle = driver.findElement(By.xpath(womenTitleXpath));
//Hover over the Menu to open it
action.moveToElement(womenTitle).build().perform();
//Wait until the menu item is visible
wait.until(ExpectedConditions.visibilityOf(By.xpath(womenCasualDressXpath)));
//Finally click on the desired element
driver.findElement(By.xpath(womenCasualDressXpath)).click();

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement