How to loop through xpath expression?

2019-12-16 20:43发布

问题:

I have a xpath expression:

referenceIn3DPage=Driver.driver.findElement(By.xpath("//div[3][@class='some-class']/div[1]//label")).getAttribute("id"); 

I want to loop from 1 to 9 for div[].

Below is my code to loop div[i] from 1 to 9:

String referenceIn3DPage =null;

int count=Driver.driver.findElements(By.xpath("//div[3][@class='some-class']//input")).size();

System.out.println("the count="+count);


for(int i=1;i<=count;i++)
{
referenceIn3DPage=Driver.driver.findElement(By.xpath("//div[3][@class='some-class']/div["+i+"]//label/input")).getAttribute("id"); 

System.out.println("the value in 3d= "+referenceIn3DPage);


}

But, it is not working as per my requirement. I want script to display OSP102 and 8 more reference ID (please refer to link given below for list of reference IDs.)

The output:

the count=9
the value in 3d= OSCP102

NOTE: Please refers to my original question for better clarity.

How to grab text corresponding to checkboxes in selenium webdriver?

回答1:

You can simplify your code by using findElements() and looping through the first 9 div elements which your xpath will fetch. Just make sure your xpath is correct.

referenceIn3DPage=Driver.driver.findElements(By.xpath("//div[3][@class='some-class']/div"));

for(WebElement e : referenceIn3DPage.sublist(0,9)) { 
    String idVal = e.findElement(By.ByTagName("label").getAttribute("id"));
    System.out.println(idVal);
}


回答2:

first check the xpath on the website and make sure its selecting the expected results.
I recommend you FireBug + FirePath which are doing a great job for that.