如何使用java访问selenium中具有相同类名的第二个元素



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

我找不到一种方法来识别这些。请让我知道在java

中识别硒webdriver中这些元素的其他方法

您可以使用xpath索引选项。

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

如果属性没有惟一性,则始终可以使用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]表示第二个同名元素

您可以使用像following-sibling/before -sibling这样的xpath方法。

例如,如果按钮位于任何唯一的web元素,尝试首先识别该web元素,并通过使用不同的xpath方法,如跟随兄弟姐妹,内容,前面兄弟姐妹,您可以访问web元素。

对相同名称和相同类的按钮进行迭代循环

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 clickedt--");
    System.out.println("pass");
    driver.navigate().back();
        
    } 
    

最新更新