如何使用 Selenium 和 Java 识别 <a> 中的文本

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

这是我要测试的演示商店的代码:

 <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>

我想获取这些子类别的文本,以便稍后可以通过使用 link 元素内的文本来单击特定类别。我的代码是:

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

但它不会进入循环,可能是因为 element.getText() 是空的。

element.getText()可以为空。

尝试:

element.getAttribute("value");
// or
element.getAttribute("innerHTML");

将您的 CSS 更改为:

"a[class*='level']";
// or
"a[]";

调试代码并检查元素是否为空

点击 with text as Shirts first you have to the element with text as Men inducing for the and you can use the following :

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