2014-01-10 123 views
0

我目前正在使用webEngine渲染一個網頁,並且想要在渲染的DOM樹上執行一個腳本,但似乎有些錯誤。下面的代碼的輸出是使用webEngine.executeScript()獲取DOM節點的innerHTML?

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

回答

0

您需要聽取特殊屬性以等待WebView加載。 Btw,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"); 
      } 
     } 
    } 
}); 
+0

謝謝!它完美的工作! – langkilde

+0

太棒了!你可能想[繼續到這裏](http://meta.stackexchange.com/a/5235/238087)。 –

+0

謝謝@andrey!我是新來的,所以我很欣賞這個建議。我問了一個後續問題,你可能知道答案http://stackoverflow.com/questions/21091107/extract-dom-element-offset-using-webengine-executescript-on-headless-server – langkilde