附加到文本文件
问题描述:
此代码将遍历多个页面以在页面上查找和提取元素。一旦循环完成,它将生成一个包含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());
}
}
任何想法?
答
map.put(element1.getText(), element1.findElement(By.tagName("a")).getAttribute("href"));
如果在HashMap中有与element1.getText()
相同文本的任何条目,它将覆盖它。
另外,您正在为每次调用创建地图,每次都会创建一个新地图,并导致早期内容丢失数据。
/* Create HashMap and store H3 elements in the key set */ this.map = new HashMap<String, String>();
您应该在实例级别创建它。
为了生成唯一键,在实例级别定义一个数字变量,并为每个放置增量。
long counter = 0;
map.put(counter++, element1.findElement(By.tagName("a")).getAttribute("href"));
可以改变HashMap只需要Key而不是String。
答
for (WebElement element1 : allElements) {
i++
map.put(element1.getText()+i, element1.findElement(By.tagName("a")).getAttribute("href"));
}
添加I ++所以它不覆盖
好了,我怎么能得到解决吗? – Nazrod12
你会如何解决这个问题? – Nazrod12
两件事情,不要在每次通话中初始化地图,否则旧数据将丢失。其次为了生成唯一的键值,你可以使用任何int/long类型的实例变量,并在每次调用之后增加它。 – ManishKr