[英]Selenium WD | How do I copy all values from a WebElement list into a String list?
I have a list that I collecting a list of stock prices that are constantly changing 我有一个清单,我在收集一个不断变化的股票价格清单
List listOfLastPrice1;
清单listOfLastPrice1;
I know that this list is not constant as the price of stocks is not constant. 我知道这个清单不是固定不变的,因为股票价格不是固定不变的。 Meaning if I print it now, and will print it again in 5 minutes, values would change.
这意味着如果我现在打印它,并且将在5分钟内再次打印,则值将发生变化。 Why?
为什么? because this is a WebElement list that is connected to the DOM directly.
因为这是一个直接连接到DOM的WebElement列表。
I have created a second list 我创建了第二个列表
ArrayList listCopyLastPrice1 = new ArrayList();
ArrayList listCopyLastPrice1 = new ArrayList();
I would like to copy all values from the WebElement list, into the String list. 我想将WebElement列表中的所有值复制到String列表中。 How do I do that?
我怎么做?
I tried several attempts but with no success 我尝试了几次但没有成功
package TestMain;
import java.util.ArrayList;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import PageObjects.Editions;
public class Test {
public void getList(WebDriver driver) {
driver.get("https:www.investing.com/Markets");
List <WebElement> listOfLastPrice1;
listOfLastPrice1= driver.findElements(By.cssSelector("[data-column-name='last'][class*='pid']"));
ArrayList<String> listCopyLastPrice1 = new ArrayList<String>();
//..........
}
}
Iterate over WebElement
list and add values to String
list 遍历
WebElement
列表并将值添加到String
列表
List <WebElement> listOfLastPrice1;
listOfLastPrice1= driver.findElements(By.cssSelector("[data-column-name='last'][class*='pid']"));
List<String> listCopyLastPrice1 = new ArrayList<String>();
for (WebElement element : listOfLastPrice1) {
listCopyLastPrice1.add(element.getText());
}
EDIT: 编辑:
Since Java 1.8 you can use Stream
API to change the list of WebElement
s to list of String
like this: 从Java 1.8开始,您可以使用
Stream
API将WebElement
的列表更改为String
列表,如下所示:
List<String> listOfLastPrice1WithStrings = driver.findElements(By.cssSelector("[data-column-name='last'][class*='pid']"))
.stream()
.map(x -> x.getText())
.collect(Collectors.toList());
No , you can't copy a List of WebElement within a List of String type. 不 ,你不能字符串类型的列表中复制WebElement的名单 。 Attempting that will raise
ClassCastException
. 尝试将引发
ClassCastException
。 But you can store any of the attributes of the WebElements (eg id, name, innerText, innerHTML) within the String type List as follows : 但是您可以将WebElement的任何属性(例如id,name,innerText,innerHTML)存储在String类型列表中 ,如下所示:
List<String> listCopyLastPrice1 = new ArrayList<String>();
List<WebElement> listOfLastPrice1 = driver.findElements(By.cssSelector("[data-column-name='last'][class*='pid']"));
for(WebElement elem:listOfLastPrice1)
listCopyLastPrice1.add(elem.getAttribute("innerHTML"));
System.out.println(listCopyLastPrice1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.