使用webEngine.executeScript()获取DOM节点的innerHTML?

时间:2014-01-10 08:13:14

标签: java javascript html dom javafx

我目前使用webEngine渲染网页,并希望在渲染的DOM树上执行脚本,但似乎有些错误。以下代码的输出是

trying to execute script
script failed

有谁知道我做错了什么?我意识到我可以用JSoup做所有这些,但后来我想用javascript找到渲染的DOM元素的坐标。这似乎是试图达到目标的良好的第一步。

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import java.net.URL;
import org.jsoup.nodes.Element;

public class Extractor extends Application {
    URL anURL;
    Element p;

    @Override
    public void start(Stage stage) throws Exception {
        URL anURL = new URL("http://www.gp.se/nyheter/varlden/1.2238540-frigivna-svenskar-landade-i-sverige");
        final WebView webView = new WebView();
        final WebEngine webEngine = webView.getEngine();
        webEngine.load(anURL.toString());
        stage.setScene(new Scene(webView));
        stage.show();

        try {
            System.out.println("trying to execute script");
            String content = (String)webEngine.executeScript("document.getElementById('articleHeader').innerHTML()");
            System.out.println(content);
            System.out.println("script successful");
        } catch (Exception e) {
            System.out.println("script failed");
        }

    }

    public static void main(String[] args) {
        launch();
    }
}

1 个答案:

答案 0 :(得分:0)

您需要侦听特殊属性才能等待WebView加载。顺便说一句,jQuery对象可在此页面找到:

webEngine.getLoadWorker().stateProperty().addListener(new ChangeListener<Worker.State>() {
    @Override
    public void changed(ObservableValue<? extends Worker.State> ov, Worker.State t, Worker.State t1) {
        if (t1 == Worker.State.SUCCEEDED) {
            try {
                System.out.println("trying to execute script");

                // fixed - innerHtml is a property, not a function
                String content = (String)webEngine.executeScript("document.getElementById('articleHeader').innerHTML");
                System.out.println(content);
                System.out.println("script successful");
            } catch (Exception e) {

                // you can also print the exception to diagnose the error
                e.printStackTrace();
                System.out.println("script failed");
            }
        }
    }
});