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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/994172/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 14:43:29  来源:igfitidea点击:

Using selenium.getBodyText() to capture HTML source, using Java, how can I save it into a HTML file locally?

javaselenium-rc

提问by JLau

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. using java, I want to save the information from getBodyText() into a html file so I can review it later
  1. 使用 selenium,我使用 getBodyText() 捕获了 html 源
  2. 使用 java,我想将 getBodyText() 中的信息保存到 html 文件中,以便稍后查看

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

我目前将 getBodyText() 存储为字符串,这是代码:

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!

提前致谢!

回答by Wayne

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.

如果你想读回你刚刚写的文件,你只需要 reader 类。

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

更新:看起来 selenium.getHtmlSource() 存在并且可以做你需要的。看到这篇文章