此代碼將遍歷多個頁面以在頁面上查找和提取元素。一旦循環完成,它將生成一個包含HashMap中這些元素的日誌文件,但結果不會被追加,而是被覆蓋。附加到文本文件
int d = new Integer(0);
for (int i = 0; i <= 100; d += 10) {
String url = Constants.FilterUrl + "&startIndex=" + d;
this.getAuthors();
driver.get(url);
if (!driver.getPageSource().contains("h3")) break;
}
/* Send HashMap values to text file */
File file = new File(Constants.FILEPATH + Constants.dateFormat.format(new Date()) + ".txt");
try{
if(!file.exists()){
System.out.println("We had to make a new file.");
file.createNewFile();
}
PrintWriter out = new PrintWriter(new FileWriter(file), true);
map.forEach((k, v) -> out.println(k + ", " + v));
out.append("************** " + "\n");
out.close();
} catch(IOException e) {
System.out.println("COULD NOT LOG!!");
}
}
public void getAuthors(){
List<WebElement> allElements = driver.findElements(By.tagName("h3"));
/* Create HashMap and store H3 elements in the key set */
this.map = new HashMap<String, String>();
for (WebElement element1 : allElements) {
map.put(element1.getText(), element1.findElement(By.tagName("a")).getAttribute("href"));
}
/* Visit pages for H3 elements and retrieve names of the authors */
for (Map.Entry<String, String> entry : map.entrySet()) {
driver.get(entry.getValue());
entry.setValue(driver.findElement(By.className("userlink-0")).getText());
}
}
任何想法?
好了,我怎麼能得到解決嗎? – Nazrod12
你會如何解決這個問題? – Nazrod12
兩件事情,不要在每次通話中初始化地圖,否則舊數據將丟失。其次爲了生成唯一的鍵值,你可以使用任何int/long類型的實例變量,並在每次調用之後增加它。 – ManishKr