Home > Net >  Add Webelement text into list by iterating each element using for loop
Add Webelement text into list by iterating each element using for loop

Time:10-05

There are 5 Webelements which share same xpaths. I want to get the text from each element and store it in a list. Below is my failed attempt:

List<WebElement> ActualAdFormats_Elements = driver.findElements(By.xpath("(//h4[text()='Select Ad Format']/..//strong)"));
for(WebElement AdFormat:ActualAdFormats_Elements) {
    ActualAdFormat_List.add(AdFormat.getText());
        }

CodePudding user response:

Not sure what is ActualAdFormat_List in your code.

Also there's no need to have parenthesis in xpath, remove them as well.

Please define a list of string like this :

List<String> ActualAdFormat_List = new ArrayList<String>();

and use it like this :

List<WebElement> ActualAdFormats_Elements = driver.findElements(By.xpath("//h4[text()='Select Ad Format']/..//strong"));
for(WebElement AdFormat : ActualAdFormats_Elements) {
    ActualAdFormat_List.add(AdFormat.getText());
        }

Make sure that,

//h4[text()='Select Ad Format']/..//strong

represent all 5 web elements in HTMLDOM.

Steps to check:

Press F12 in Chrome -> go to element section -> do a CTRL F -> then paste the xpath and see, if your desired element is getting highlighted with 1/1 matching node.

  • Related