String name = "";
String width = "";
String height = "";
List<WebElement> imageName = driver.findElements(By.cssSelector("div.card-arago div.hover-info div.name"));
List<HashMap> imageInfo = new ArrayList<HashMap>();
HashMap<String, String> attributes = new HashMap<String, String>();
imageInfo.add(attributes);
for (WebElement image : imageName) {
attributes.put("name",image.getText());
}
List<WebElement> images = driver.findElements(By.cssSelector("div.card-arago a img"));
for (WebElement image : images) {
attributes.put("width", image.getAttribute("width"));
attributes.put("height", image.getAttribute("height"));
}我试图返回页面中的所有图像,但它只返回页面上的最后一个图像卡?
发布于 2016-05-14 03:59:26
对于每个键,HashMap只能存储一个值。如果使用相同的键多次调用put,则每次调用都会覆盖前一次调用。您在循环中多次调用attributes.put("name", ...),因此附加到键"name“的值被一次又一次地替换,并且在循环的末尾只剩下最后一个图像。如果您实际上希望返回所有图像,则需要为每个图像提供唯一的键,或者为每个图像提供一个完全独立的HashMap,这取决于您希望如何构造它。
编辑:在进一步查看您的代码之后,看起来您确实想要一个HashMaps列表。但您只会在该列表中添加一个HashMap。相反,您可以更改第一个循环,为每个图像添加一个新HashMap。
发布于 2016-05-14 04:07:25
当调用put(k,v);时,key被存储,value是额外的元数据。只有一个键和一个值。如果我调用put(1,2);,然后调用put(1,3);,get(1);返回的值将是3。put(k,v);函数只在HashMap中存储不同的对象。您不能在同一HashMap中具有相同的值,但是,您可以在同一HashMap中具有相同的值。
为了解决您的问题,我建议您使用像这样的标识符
attributes.put("width" + someIntIdentifier, image.getAttribute("width");发布于 2016-05-14 12:32:54
您正在使用一个map并不断更新键值,对于一个key,一个map只能有一个值(它替换以前的值)。或者,您可以尝试使用地图列表,该列表将包含包含有关图像的信息的地图。
String name = "";
String width = "";
String height = "";
List imageNameList = new ArrayList(); // creating list to store imageName
List imageAttributesList = new ArrayList(); // creating list to store image height and width
List<WebElement> imageName = driver.findElements(By.cssSelector("div.card-arago div.hover-info div.name"));
List<HashMap> imageInfo = new ArrayList<HashMap>();
imageInfo.add(attributes);
for (WebElement image : imageName) {
HashMap<String, String> attributes = new HashMap<String, String>();
attributes.put("name",image.getText());
imageNameList.add(attributes); // adding map to list
}
List<WebElement> images = driver.findElements(By.cssSelector("div.card-arago a img"));
for (WebElement image : images) {
HashMap<String, String> attributes = new HashMap<String, String>();
attributes.put("width", image.getAttribute("width"));
attributes.put("height", image.getAttribute("height"));
imageAttributesList.add(attributes); // adding map to list
}
System.out.println(imageNameList); // this will give you a list of Map having "name" key
System.out.println(imageAttributesList); // this will give you a list of Map having "height" and "width" of image这里我创建了两个列表来存储图像名称和高度和宽度。这样你就可以获得你需要的所有图像的属性。
https://stackoverflow.com/questions/37218336
复制相似问题