[英]Downloading images using selenium webdriver
我正在嘗試從這樣的網站下載圖像:
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();
}
}
}
保存圖片時,它會覆蓋上一張圖片。 我該如何解決這個問題? 任何幫助將不勝感激,謝謝。
也許這可以幫助:
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();
}
}
希望這會有所幫助。
快樂編碼:)
在循環外聲明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"
太多的+
連續我喜歡和遞增內聯。 我更喜歡:
countF++;
new File(countF + ".jpg"));
但這只是我的個人風格,兩者都應該有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.