Java GUI中显示网页和HTML返回 [英] Java GUI to display webpages and return HTML
问题描述
我需要一个工作流程如下图所示:
I need a workflow like below:
// load xyz.com in the browser window
// the browser is live, meaning users can interact with it
browser.load("http://www.google.com");
// return the HTML of the initially loaded page
String page = browser.getHTML();
// after some time
// user might have navigated to a new page, get HTML again
String newpage = browser.getHTML();
我很惊讶地发现这是多么辛苦与Java的GUI做的,如JavaFX的(的 http://lexandera.com/2009/01/extracting-html-from-a-webview/ )和Swing。
有一些简单的方法来获得在Java中此功能?
Is there some simple way to get this functionality in Java?
推荐答案
下面是使用JavaFX,打印HTML内容到System.out一个人为的例子 - 它不应该太复杂,以适应创建一个 getHtml()
方法。 (我使用JavaFX 8测试它,但它应该使用JavaFX 2工作太)。
Here is a contrived example using JavaFX that prints the html content to System.out - it should not be too complicated to adapt to create a getHtml()
method. (I have tested it with JavaFX 8 but it should work with JavaFX 2 too).
在code将打印HTML内容每次一个新的页面被加载。
The code will print the HTML content everytime a new page is loaded.
请注意:我已经借了从 的PrintDocument
code这个答案。
Note: I have borrowed the printDocument
code from this answer.
public class TestFX extends Application {
@Override
public void start(Stage stage) throws Exception {
try {
final WebView webView = new WebView();
final WebEngine webEngine = webView.getEngine();
Scene scene = new Scene(webView);
stage.setScene(scene);
stage.setWidth(1200);
stage.setHeight(600);
stage.show();
webEngine.getLoadWorker().stateProperty().addListener(new ChangeListener<Worker.State>() {
@Override
public void changed(ObservableValue<? extends State> ov, State t, State t1) {
if (t1 == Worker.State.SUCCEEDED) {
try {
printDocument(webEngine.getDocument(), System.out);
} catch (Exception e) { e.printStackTrace(); }
}
}
});
webView.getEngine().load("http://www.google.com");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void printDocument(Document doc, OutputStream out) throws IOException, TransformerException {
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
transformer.transform(new DOMSource(doc), new StreamResult(new OutputStreamWriter(out, "UTF-8")));
}
public static void main(String[] args) {
launch(args);
}
}
这篇关于Java GUI中显示网页和HTML返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!