How to identify the text within the <a> using Selenium and Java

Viewed 98

This is the code of the demo store I want to test:

 <li class="level0 nav-2 parent">
      <a href="http://demo-store.seleniumacademy.com/men.html" 
               class="level0 has-children">Men</a> 
        <ul class="level0">
            <li class="level1 view-all">
               <a class="level1" href="http://demo- 
                         store.seleniumacademy.com/men.html">View All 
                         Men</a>
            </li>
               <li class="level1 nav-2-1 first"><a></a></li>
               <li class="level1 nav-2-2"><a href="http://demo- 
                          store.seleniumacademy.com/men/shirts.html" 
                          class="level1">text to get</a> 
               </li>
               <li class="level1 nav-2-3"><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.

2 Answers

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

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);
}
Related