[英]Using webElement(Selenium) get all 'x'-tags content as a list
I get a webElement with:我得到一个 webElement:
WebElement myElement = browser.findElement(By.cssSelector(".nd_list"));
Html of element is something like:元素的 HTML 类似于:
<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. web 元素有更多的 html-body,只是为了制作一个视图......这个想法是我想要一些动态的东西。 I want to get all
<span>
elements from myElement
and put their content into an array of int.我想从
myElement
获取所有<span>
元素并将它们的内容放入一个 int 数组中。 Expected result: int [] myArray = {2,3}
How can I do that, please?预期结果:
int [] myArray = {2,3}
我该怎么做?
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.执行此操作的一种方法是创建一个 CSS 选择器,以获取您所引用的
.nd_list
DIV
所有SPAN
子项。 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
.就像遍历该集合一样简单,使用
.getText()
从每个元素获取文本,然后将String
转换为int
。 I tested the code below on your HTML and it worked.我在你的 HTML 上测试了下面的代码,它工作正常。
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 :要从myElement获取所有
<span>
元素并将它们的内容放入整数数组并打印它们,您可以使用以下代码块:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.