使用selenium.getBodyText()来捕获HTML源代码,使用Java,如何在本地将其保存为HTML文件?

时间:2021-05-15 09:56:05

This is probably a java noob question but here is my scenario:

这可能是一个java noob问题,但这是我的场景:

  1. using selenium, I captured the html source with getBodyText()
  2. 使用selenium,我用getBodyText()捕获了html源代码

  3. using java, I want to save the information from getBodyText() into a html file so I can review it later
  4. 使用java,我想将getBodyText()中的信息保存到html文件中,以便稍后查看

I currently have getBodyText() stored as a String, here's the code:

我目前将getBodyText()存储为String,这里是代码:

String stored_report = selenium.getBodyText();

File f = new File("C:/folder/" + "report" + ".html");
FileWriter writer = new FileWriter(f);
writer.append(stored_report);
System.out.println("Report Created is in Location : " + f.getAbsolutePath())
writer.close();

Do I have to use FileReader? What do I need to do so the saved html file still shows the html format? (currently since it's stored as a string, the page shows up with everything appear on one line)

我必须使用FileReader吗?我需要做什么才能保存的html文件仍显示html格式? (目前因为它存储为字符串,所以页面显示所有内容都出现在一行中)

Thanks in advance!

提前致谢!

1 个解决方案

#1


Change to the following:

更改为以下内容:

String stored_report = selenium.getBodyText();

File f = new File("C:/folder/" + "report" + ".html");
FileWriter writer = new FileWriter(f,true);
writer.write(stored_report);
System.out.println("Report Created is in Location : " + f.getAbsolutePath())
writer.close();

Your code looked sound except for appending operations. Using FileWriter(f,true) gives us appending operations on the write.

除了附加操作之外,您的代码看起来很合理。使用FileWriter(f,true)可以在写入时附加操作。

You only need the reader class if you want to read back the file you just wrote.

如果要读回刚才写的文件,则只需要读者类。

Update: Looks like selenium.getHtmlSource() exists and may do what you require. See This Post

更新:看起来selenium.getHtmlSource()存在并且可以执行您需要的操作。见本文

#1


Change to the following:

更改为以下内容:

String stored_report = selenium.getBodyText();

File f = new File("C:/folder/" + "report" + ".html");
FileWriter writer = new FileWriter(f,true);
writer.write(stored_report);
System.out.println("Report Created is in Location : " + f.getAbsolutePath())
writer.close();

Your code looked sound except for appending operations. Using FileWriter(f,true) gives us appending operations on the write.

除了附加操作之外,您的代码看起来很合理。使用FileWriter(f,true)可以在写入时附加操作。

You only need the reader class if you want to read back the file you just wrote.

如果要读回刚才写的文件,则只需要读者类。

Update: Looks like selenium.getHtmlSource() exists and may do what you require. See This Post

更新:看起来selenium.getHtmlSource()存在并且可以执行您需要的操作。见本文