java - 如何从 Webview Javafx 获取元素
问题描述
我有一个应用程序,我通过链接为网站提供值,然后应用程序向我显示一张地图并在给定值之间绘制一条折线。所以我现在需要的是我必须从 Webview 中提取特定的值,所以在这篇文章How to get the value of a Java variable to javascript in JavaFX webView? 他们使用 getDocument 但我不理解代码,这就是为什么我不能很好地使用它。有人可以帮助我吗?
显示地图的代码:
@FXML
void openHtmlfile(ActionEvent event) {
WebEngine webEngine = webView.getEngine();
webEngine.javaScriptEnabledProperty().set(true);
webEngine.load("https://www.luftlinie.org/"+ fromTextField.getText() +"/"+ toTextField.getText());
;
}
从 texfields 中给出值并填充它们的方法
void fillFields(ActionEvent event) {
String startAirport = null;
String targetAirport = null;
String startCountry = null;
String targetCountry = null;
Statement airport;
try {
airport = connection.createStatement();
ResultSet MyRsAirport = airport.executeQuery("select * from fluglinie where ID =\""
+ idFlightRoute.getValue() + "\" AND fluggesellschaft =\"" + fluggesellschaft + "\"");
while (MyRsAirport.next()) {
startAirport = MyRsAirport.getString("startFlughafen");
targetAirport = MyRsAirport.getString("zielFlughafen");
}
Statement country;
country = connection.createStatement();
ResultSet MyRsCountry = country.executeQuery("select * from flughaefen");
while (MyRsCountry.next()) {
if (MyRsCountry.getString("name").equals(startAirport)) {
startCountry = MyRsCountry.getString("country");
} else if (MyRsCountry.getString("name").equals(targetAirport)) {
targetCountry = MyRsCountry.getString("country");
}
}
fromTextField.setText(startAirport + ", " + startCountry);
toTextField.setText(targetAirport + ", " + targetCountry);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
我现在要做的是例如在这两点之间计算出一个距离,我想提取它。我知道我必须使用特定 html 元素的 id 但如何在 java 中显示它?
解决方案
永远记住,官方文档是你的朋友。
首先,您需要等待页面完全加载。您可以通过观察 WebEngine 的load worker来做到这一点,它在完成时将具有SUCCEEDED状态。WebEngine 文档中详细描述了这种方法。
webEngine.getLoadWorker().stateProperty().addListener(
(o, oldState, newState) -> {
if (newState == Worker.State.SUCCEEDED) {
// ...
}
});
webEngine.load("https://www.luftlinie.org/"+ fromTextField.getText() +"/"+ toTextField.getText());
重要提示:您必须在加载页面之前添加 loadWorker 侦听器。
一旦加载工作程序成功完成,您就可以安全地访问 WebEngine 的文档,其中包含整个加载页面。您可以使用命名方便的getElementById方法搜索具有特定 ID 的元素:
webEngine.getDocument().getElementById("some-page-specific-ID")
您应该传递的确切字符串取决于页面。您可以检查页面的来源并发现id
您想要其内容的元素的来源。
如果元素没有id
属性,您将不得不依赖文档的结构并使用XPath来查找感兴趣的 HTML 元素。有关 XPath 使用的教程会使这个答案变得过大,但您可以通过阅读规范自行了解。阅读它需要具备 XML 的工作知识。
找到元素后,从中提取信息将取决于它是什么类型的元素。如果只是文本,则可以使用元素的getTextContent()方法。
所以,整体代码看起来像这样:
webEngine.getLoadWorker().stateProperty().addListener(
(o, oldState, newState) -> {
if (newState == Worker.State.SUCCEEDED) {
Document doc = webEngine.getDocument();
Element element = doc.getElementById("some-page-specific-ID");
String value = element.getTextContent();
// Display value ...
}
});
webEngine.load("https://www.luftlinie.org/"+ fromTextField.getText() +"/"+ toTextField.getText());