【问题标题】:How to access the second element that has the same class name in selenium using java如何使用java访问selenium中具有相同类名的第二个元素
【发布时间】:2022-01-04 15:07:03
【问题描述】:

在尝试自动化我们的应用程序时,有两个同名的按钮。

我无法找到识别这些的方法。请让我知道在 java 中的 selenium webdriver 中识别这些元素的其他方法是什么

【问题讨论】:

标签: java selenium selenium-webdriver


【解决方案1】:

如果属性没有唯一性,您可以始终使用 xpath。例如如果你想找到一个包含文本 foo 和名称 button 的元素,那么如果名称不是唯一的,我会喜欢下面的 xpath:

//*[@name='button' and text()='foo'] 

或者不同类但同名

//button[@name='button' and @class='xyz']

或用于不同的文本但名称相同

//input[@name='button' and contains(text(),'Click Here')]

或用于不同的标签但名称相同

//button[@name='button']
//input[@name='button']

只需使用任何独特的属性并制作自定义的 xpath。

我希望您也可以为此使用 java 脚本,例如

WebElement butttonToClick = driver.findElement(By.name("button"));
((JavascriptExecutor)driver).executeScript("arguments[1].click();",butttonToClick );

其中arguments[1] 表示第二个具有相同名称的元素。

【讨论】:

    【解决方案2】:

    您可以使用 xpath 索引选项。

    By.xpath("(//input[@name='Button'])[2]")
    

    【讨论】:

      【解决方案3】:

      您可以使用 xpath 方法,例如后续兄弟/前面的兄弟。

      例如,如果 Button 位于任何唯一的 web 元素,请尝试首先识别该 web 元素,并通过使用不同的 xpath 方法(如跟随兄弟、内容、前面的兄弟)来访问该 web 元素。

      【讨论】:

        【解决方案4】:

        在具有相同名称和相同类的按钮上迭代循环

        List<WebElement> listofItems= 
        driver.findElements(By.className("actions")); 
        System.out.println(listofItems);
        System.out.println(listofItems.size());
        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
        for (int s=1; s<=listofItems.size(); s++)
        { 
         /*Getting the list of items again so that when the page is
           navigated back to, then the list of items will be refreshed
           again */ 
           listofItems= driver.findElements(By.className("actions")); 
               
           //Waiting for the element to be visible
           //Used (s-1) because the list's item start with 0th index, like in 
             an array
            wait.until(ExpectedConditions.visibilityOf(listofItems.get(s-1)));
        
          //Clicking on the first element 
            listofItems.get(s-1).click();
            Thread.sleep(2000);
            driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
            System.out.print(s + " element clicked\t--");
            System.out.println("pass");
            driver.navigate().back();
                
            } 
            
        

        【讨论】:

          猜你喜欢
          • 2019-11-26
          • 2014-07-12
          • 2022-10-31
          • 1970-01-01
          • 1970-01-01
          • 2018-04-12
          • 1970-01-01
          • 2016-07-11
          相关资源
          最近更新 更多