我正试图从这样的网站下载图片:
List <WebElement> listofItems = driver.findElements(By.cssSelector("div.heroThumbnails:nth-child(4) > div:nth-child(2) > div:nth-child(n)"));
URL imageURL = null;
for(WebElement myElement : listofItems) {
String j = myElement.getAttribute("data-bigurl");
System.out.println(j);
for(int i = 0; i < listofItems.size(); i++){
try {
//generate url
imageURL = new URL(j);
int countF = 0;
//read url and retrieve image
BufferedImage saveImage = ImageIO.read(imageURL);
//download image to the workspace where the project is, save picture as picture.png (can be changed)
ImageIO.write(saveImage, "jpg", new File(countF++ + ".jpg"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
保存图片时,它会覆盖上一张图片。我怎样才能解决这个问题?任何帮助将不胜感激,谢谢。
答案 0 :(得分:3)
也许这可能会有所帮助:
ImageIO.write(saveImage, "jpg", new File(i + ".jpg"));
我猜你会覆盖因为你给他们相同的名字。
所以你可以使用循环计数器(顶部的行)或只是在外面声明你的countF
:
int countF = 0;
for(int i = 0; i < listofItems.size(); i++) {
try {
// all your stuff here
// ...
// this will create an image with new name each time
ImageIO.write(saveImage, "jpg", new File(countF + ".jpg"));
countF++;
} catch (IOException e) {
e.printStackTrace();
}
}
希望这有帮助。
快乐编码:)
答案 1 :(得分:1)
在循环外声明您的 Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/
Raised by: django.contrib.staticfiles.views.serve
'index.html' could not be found
变量,以便在图像之间保留其值。
countF
不相关:此代码有点主题 int countF = 0;
for(int i = 0; i < listofItems.size(); i++){
try {
//generate url
imageURL = new URL(j);
//read url and retrieve image
BufferedImage saveImage = ImageIO.read(imageURL);
//download image to the workspace where the project is, save picture as picture.png (can be changed)
ImageIO.write(saveImage, "jpg", new File(countF++ + ".jpg"));
} catch (IOException e) {
e.printStackTrace();
}
}
我个人不喜欢new File(countF++ + ".jpg"));
我的喜好和内联递增太多countFF++ + ".jpg"
。我更喜欢:
+
但这只是我的个人风格,两者都应该有用。