Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

  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

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

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)

Thanks in advance!

like image 663
JLau Avatar asked May 26 '26 05:05

JLau


1 Answers

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.

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

like image 83
Wayne Avatar answered Jun 04 '26 22:06

Wayne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!