【问题标题】:How to print the all li items text of dropdown using Selenium WebDriver?如何使用 Selenium WebDriver 打印下拉列表的所有 li 项文本?
【发布时间】:2014-12-27 12:13:17
【问题描述】:

我如何使用 selenium webdriver 打印所有 li 项目文本。 在这里,我想要某种类型的单行代码,打印所有 li 项目文本,如

  • 夹克,
  • 保护等。可以使用for循环

    <div class="dropdown  change_right">
     <ul>            
        <li>
            <a class="" title="Jackets" href="/collections/jackets">Jackets</a> 
        </li>
        <li>
            <a title="Jackets protective" href="/collections/jackets/jackets-protective" class="sub-link"> protective</a>
        </li>
        <li> 
            <a title="casual leather" href="/collections/jackets/casual-leather" class="sub-link">casual leather</a>
        </li>
        <li>
            <a class="" title="T-shirts &amp; shirts " href="/collections/t-shirts-shirts">T-shirts &amp; shirts </a>
        </li>
        <li> 
            <a title="shirts" href="/collections/t-shirts-shirts/shirts" class="sub-link">shirts</a>
        </li>
        <li>
            <a title="crew-neck" href="/collections/t-shirts-shirts/crew-neck" class="sub-link">crew-neck</a>
        </li>
        <li>
            <a title="polo tshirts" href="/collections/t-shirts-shirts/polo-tshirts" class="sub-link">polo tshirts</a>
        </li>
        <li>
            <a class="" title="Trousers" href="/collections/trousers">Trousers</a>
        </li>
        <li>
            <a title="Trousers Protective" href="/collections/trousers/trousers-protective" class="sub-link"> Protective</a>
        </li>
    </ul>
    

【问题讨论】:

    标签: java eclipse selenium selenium-webdriver


    【解决方案1】:

    可以通过简单的findElements() 来完成。在xpath 的帮助下获取elements 的集合并简单地遍历集合并在getText() 的帮助下打印值,它返回元素的字符串值。

    List<WebElement> allText = driver.findElements(By.xpath("//*[contains(@class,'dropdown')]//a"));
    for ( WebElement element: allText) { 
        System.out.println(element.getText());
    }
    

    注意:未经测试的代码。您可能需要确保在执行此代码之前单击并打开列表,并且可能还需要等待

    【讨论】:

    • 您可以获取整个类属性值或部分属性值,例如class='foo foo2',您可以使用//*[contains(@class,'foo2')]//a//*[contains(@class,'foo')]//a。如果这是您想要的,请告诉我
    • 这个代码是正确的。但是我的菜单下拉项是隐藏的,当下拉父菜单项通过鼠标图标悬停时,项目是可见的。请为此做点什么
    • 试试Action builder。这是将鼠标悬停在问题上的解决方法..By byXpath = By.xpath ("xpath for the element to hover over") WebElement element = driver.findElement(By.xpath(byXpath)); Actions action = new Actions(driver); action.moveToElement(element).build().perform();
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-14
    • 1970-01-01
    相关资源
    最近更新 更多