简体   繁体   中英

Get innerHTML of DOM node using webEngine.executeScript()?

I currently render a webpage using webEngine and want to execute a script on the rendered DOM tree, but something seems to be wrong. The output of the code below is

trying to execute script
script failed

Does anyone know what I'm doing wrong? I realize I could do all of this with JSoup but later on I want to find the coordinates of rendered DOM elements using javascript. This seems like a good first step in trying to get there.

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();
    }
}

You need to listen to a special property to wait for WebView to load. Btw, jQuery object is available at this page:

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");
            }
        }
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM