简体   繁体   中英

List.get(index) to extend xpath for another List <WebElement>

I need to initialize List with a value of another List with its index from a loop

I have already tried the snippet below:

List <WebElement> row = driver.findElements(By.xpath("//*[@id='row']"));
for (int x=0; x<row.size(); x++){
String value = row.get(x).findElements(xpath to extend that element).get(x).getText() //just a sample manipulation

// THEN HERE'S THE PROBLEM
//I NEED TO EXTEND AGAIN THE LIST TO ANOTHER LIST
List <WebElement> another_row = row.get(x).findElements('//*[@class='house active' or @class='house']//*[contains(@id,'room')]')
//another for loop for another_row 
}

The problem is the row.get(x) part is not working. I'm getting all the nodes in the first list adding to the new list.

EDIT: My problem is somewhat like this but in List <WebElement> and in loop

You can do it by taking a parent xpath and then passing that parent xpath to the xpath of the child elements which you want to fetch.

List<WebElement> parentElements = driver.findElements(By.xpath("xpath of the parent element"));
List<WebElement> childElements = parentElements.get(0).findElements(By.xpath("xpath of the child element"));

And if in your case you are getting all the nodes in the first list adding to the new child list, then you can directly fetch the first element of the parent by using the index in the xpath, like:

WebElement parentElement = driver.findElement(By.xpath("(//*[@id='row'])[1]"));

And you can also parameterise the index of the element like:

int i = 1;
WebElement parentElement = driver.findElement(By.xpath("(//*[@id='row'])["+i+"]"));

And now with this parent element you can fetch the child list elements like:

List<WebElement> childElements = parentElement.findElements(By.xpath("xpath of the child element"));

Since you are tryign to find elements from previous WebElement , that suggests you are searching for nested elements. Starting XPath with // means "anywhere on the current page". This is very likely not what you want.

Adding a single dot at the start of your nested XPath, so .// means "anywhere relative to the previous element". This is much more likely what you want.

This is also explained in the official documentation :

When using xpath be aware that webdriver follows standard conventions: a search prefixed with "//" will search the entire document, not just the children of this current node. Use ".//" to limit your search to the children of this WebElement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM