简体   繁体   中英

Using webElement(Selenium) get all 'x'-tags content as a list

I get a webElement with:

WebElement myElement = browser.findElement(By.cssSelector(".nd_list"));

Html of element is something like:

<div class="nd_list">
  <div>etc</div>
  <table>
    <span>2</span>
  </table>

  <table>
    <span>3</span>
  </table>
</div>

The web element have more html-body, is just for make aa view...The idea is that I want something dynamic. I want to get all <span> elements from myElement and put their content into an array of int. Expected result: int [] myArray = {2,3} How can I do that, please?

One way to do this would be to create a CSS selector that gets all SPAN children of the .nd_list DIV you referred to. It's as simple as looping through that collection, getting the text from each element using .getText() , and then converting the String to an int . I tested the code below on your HTML and it worked.

List<WebElement> spans = driver.findElements(By.cssSelector(".nd_list span"));
int[] numbers = new int[spans.size()];
for (int i = 0; i < spans.size(); i++)
{
    numbers[i] = Integer.parseInt(spans.get(i).getText());
    System.out.println(numbers[i]);
}

To get all <span> elements from myElement and put their content into an integer array and print them you can use the following code block :

List<WebElement> myElement = driver.findElements(By.cssSelector(".nd_list table > span"));
List<Integer> myList = new ArrayList<Integer>();
for(WebElement ele:myElement)
    myList.add(Integer.parseInt(ele.getAttribute("innerHTML")));
Integer[] myArray = myList.toArray(new Integer[0]);
System.out.println(myArray);

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