我想点击这些项目,但我希望减少代码中的行数。我该怎么做。此外,我想在下面的所有元素上运行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();
答案 0 :(得分:0)
假设您使用 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 可能会陷入困境。
答案 1 :(得分:0)
我在下面的代码中使用了数组概念。它将点击每组中的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();
}
}
}
}