This is the code of the demo store I want to test:
<li >
<a href="http://demo-store.seleniumacademy.com/men.html"
>Men</a>
<ul >
<li >
<a href="http://demo-
store.seleniumacademy.com/men.html">View All
Men</a>
</li>
<li ><a></a></li>
<li ><a href="http://demo-
store.seleniumacademy.com/men/shirts.html"
>text to get</a>
</li>
<li ><a></a></li>
</ul>
</li>
I want to get text of those subcategories so I can later click on specific category by using text inside of a link element. My code is:
public Subcategory openSubcategory (String subcategoryName){
List<WebElement> subcategories = driver.findElements(By.cssSelector("a.level1"));
for (WebElement element: subcategories) {
if (element.getText().equals(subcategoryName)){
element.click();
break;
}
}
return new Subcategory(driver);
}
But it won't go inside loop, probably because element.getText()
is empty.
CodePudding user response:
element.getText() can be empty.
Try:
element.getAttribute("value");
// or
element.getAttribute("innerHTML");
Change your CSS to be:
"a[class*='level']";
// or
"a[]";
Debug the code and check if the element is not null
CodePudding user response:
To click on the WebElement with text as Shirts first you have to Mouse Hover the element with text as Men inducing WebDriverWait for the visibilityOfElementLocated and you can use the following locator strategies:
public Subcategory openSubcategory (String subcategoryName){
WebElement menuMen = new WebDriverWait(driver, 10).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//a[contains(@class,'has-children') and text()='Men']")));
new Actions(driver).moveToElement(menuMen).build().perform();
List<WebElement> subcategories = driver.findElements(By.xpath("//a[contains(@class,'has-children') and text()='Men']//following::ul[1]//li/a"));
for (WebElement element: subcategories) {
if (element.getText().equals(subcategoryName)){
element.click();
break;
}
}
return new Subcategory(driver);
}