Selenium Webdriver:我想要一个替代方案,我想连续点击按钮

Selenium Webdriver : I want an alternative and i want to click on the buttons continously

我想点击项目,但我想减少代码行数。我该怎么做。另外我想运行在下面的所有元素上点击操作5次

driver.findElement(By.xpath(".//*[@id='fp-nav']/ul/li[1]/a/span")).click();
    driver.findElement(By.xpath(".//*[@id='fp-nav']/ul/li[2]/a/span")).click();
    driver.findElement(By.xpath(".//*[@id='fp-nav']/ul/li[3]/a/span")).click();
    driver.findElement(By.xpath(".//*[@id='fp-nav']/ul/li[4]/a/span")).click();
    driver.findElement(By.xpath(".//*[@id='fp-nav']/ul/li[5]/a/span")).click();
    driver.findElement(By.xpath(".//*[@id='fp-nav']/ul/li[6]/a/span")).click();
    driver.findElement(By.xpath(".//*[@id='fp-nav']/ul/li[7]/a/span")).click();
    driver.findElement(By.xpath(".//*[@id='fp-nav']/ul/li[8]/a/span")).click();
    driver.findElement(By.xpath(".//*[@id='fp-nav']/ul/li[9]/a/span")).click();
    driver.findElement(By.xpath(".//*[@id='fp-nav']/ul/li[10]/a/span")).click();

假设您使用 JAVA 作为语言,请查看以下代码是否对您有所帮助:

int i;
try{
    WebElement ele;
    //Iterating through all the 10 elements
    for(i=1;i<=10;i++){
        ele = driver.findElement(By.xpath("//*[@id='fp-nav']/ul/li["+i+"]/a/span"));
        //Clicking 5 times on the element
        for(int j=1;j<=5;j++){
                ele.click();
        }
    }
}catch(Throwable e){
    System.out.println("Error came up while clicking the element with xpath: '"+"//*[@id='fp-nav']/ul/li["+i+"]/a/span'"+". "+e.getMessage());
}

注意:它将遍历所有 10 个元素并单击每个元素 5 次。这里可能出现的唯一问题是,如果单击导致 DOM 更改,那么 StaleElementReferenceException 可能会出现冲突。

我在下面的代码中使用了数组概念。每组将点击 10 个项目(5 次)。

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class clickitems 
{
public static void main(String[] args) 
{
   String[] element={".//*[@id='fp-nav']/ul/li[1]/a/span", ".//*[@id='fp-nav']/ul/li[2]/a/span",".//*[@id='fp-nav']/ul/li[3]/a/span", ".//*[@id='fp-nav']/ul/li[4]/a/span", ".//*[@id='fp-nav']/ul/li[5]/a/span", ".//*[@id='fp-nav']/ul/li[6]/a/span", ".//*[@id='fp-nav']/ul/li[7]/a/span", ".//*[@id='fp-nav']/ul/li[8]/a/span", ".//*[@id='fp-nav']/ul/li[9]/a/span", ".//*[@id='fp-nav']/ul/li[10]/a/span"};
   WebDriver driver = new ChromeDriver(); // Modify according to your browser
   for(int i = 1; i < 6 ; i++){
       System.out.println("Count : "+ i);
       for(int j = 0; j < element.length ; j++)
        {
         System.out.println(element[j]);
         driver.findElement(By.xpath(element[j])).click();
        }
     }
   }
  }