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"?
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"?
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();
Here is a quick python script that clicks that "Casual Dresses" button. You have to use ActionChains to hover over "Women", then identify and click "Casual Dresses":
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
import time
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains
driver = webdriver.Chrome(ChromeDriverManager().install())
driver.get("http://automationpractice.com/index.php")
womenElement = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, 'a[title="Women"]')))
ActionChains(driver).move_to_element(womenElement).perform()
casualDressesElement = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, 'a[title="Casual Dresses"]')))
casualDressesElement.click()
time.sleep(5)
driver.quit()
You can find by reading the <li> items,this is my result:
xpath:
//*[@id="block_top_menu"]/ul/li[1]/ul/li[2]/ul/li[1]/a
full xpath:
/html/body/div/div[1]/header/div[3]/div/div/div[6]/ul/li[1]/ul/li[2]/ul/li[1]/a