【问题标题】:How to select an element using selenium which does not contain a particular class如何使用不包含特定类的 selenium 选择元素
【发布时间】:2018-12-04 16:45:59
【问题描述】:

我有以下 HTML 代码。

<ul class="options">
    <li class="first popover-options ">data</li>
    <li class="first popover-options disabled">data2</li>
    <li class="first popover-options ">data3</li>
</ul>

我需要选择具有 class="first popover-options" 的元素,即它不应该包含禁用。如何在 java 中使用 selenium?

【问题讨论】:

  • select the element 但有多个元素与with class="first popover-options"
  • 有两个元素提到了class,data和data3,你要选择哪一个?
  • @DebanjanB,我需要选择任何元素,唯一的要求是它不应该被禁用。他们没有具体要求选择任何数据或数据3。它可以选择两者中的任何一个。
  • @cruisepandey 可以是两者中的任何一个。

标签: java selenium selenium-webdriver xpath css-selectors


【解决方案1】:

根据您的问题要根据您共享的 HTML 来识别带有 class="first popover-options" 且不应包含 disabled 的任何元素,您可以创建一个 List使用以下任一解决方案匹配条件的元素:

  • 使用cssSelector

    for (WebElement element:driver.findElements(By.cssSelector("ul.options>li.first.popover-options:not(.disabled)"))) 
    {
        //perform any action with the elements from the list
    }
    
  • 使用xpath

    for (WebElement element:driver.findElements(By.xpath("//ul[@class='options']//li[@class='first popover-options']"))) 
    {
        //perform any action with the elements from the list
    }
    

【讨论】:

    【解决方案2】:

    你可以试试这个代码

    List<WebElement> ListEle=  driver.findElements(By.cssSelector("li.first popover-options"));
    for (WebElement tempEle : ListEle) {
        if(tempEle.getText().contains("Data"))
         {
           tempEle.click();
         }    
       }
    

    注意它会从下拉列表中选择数据,如果您想从下拉列表中选择任何其他项目,您可以通过替换此级别的代码来获得它:tempEle.getText().contains("Data")

    【讨论】:

    • 谢谢,但数据内容是动态的,所以这是个问题。
    【解决方案3】:

    您可以使用LIST 选择多个元素,然后选择对所选项目的操作。

    示例代码如下:

    List<WebElement> ListEle=  driver.findElements(By.xpath("//ul[@class='options']//li[@class='first popover-options']"));
    for (WebElement tempEle : ListEle) {
        if(conditions)
         {
           //statemnets
           Break;
         }    
       }
    

    【讨论】:

      猜你喜欢
      • 2017-05-21
      • 2014-11-02
      • 1970-01-01
      • 2018-06-15
      • 1970-01-01
      • 1970-01-01
      • 2012-12-01
      • 2017-09-20
      • 1970-01-01
      相关资源
      最近更新 更多