gpt4 book ai didi

java - 附加到文本文件

转载 作者:行者123 更新时间:2023-11-30 07:01:08 24 4
gpt4 key购买 nike

此代码将遍历多个页面以查找并提取页面上的元素。循环完成后,它将生成一个日志文件,其中包含 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() 具有相同文本的条目,它将覆盖它。

此外,您还要为每次调用创建 map ,它每次都会创建一个新的 map ,并导致早期内容的数据丢失。

/* 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 更改为使用较长的键而不是字符串。

关于java - 附加到文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40907322/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com