JavaFX WebEngine parse HTML document

Description

JavaFX WebEngine parse HTML document

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Worker.State;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;

public class Main extends Application {
   public static void main(String[] args) {
      Application.launch(args);/*from w ww  .  j av a  2s. co m*/
   }

   @Override
   public void start(Stage primaryStage) {
      VBox vb = new VBox();
      vb.setId("root");

      WebView browser = new WebView();
      WebEngine engine = browser.getEngine();
      String url = "https://www.demo2s.com/java/javafx-lineargradient-create.html";
      engine.load(url);
      
      engine.getLoadWorker().stateProperty().addListener(new ChangeListener<State>() {
         public void changed(ObservableValue<? extends State> observable, State oldValue, State newValue){
             System.out.println("done!" + newValue.toString());
             if (newValue != State.SUCCEEDED) {
                 return;
             }
             
             parse(engine.getDocument());
         }
         });
             

      vb.setPadding(new Insets(30, 50, 50, 50));
      vb.setSpacing(10);
      vb.setAlignment(Pos.CENTER);
      vb.getChildren().addAll(browser);

      Scene scene = new Scene(vb);
      primaryStage.setScene(scene);
      primaryStage.show();
   }
   private static void parse(Document doc) {
      
      NodeList currWeatherLocation = doc.getElementsByTagNameNS("https://your domain.com/ns/rss/1.0", "location");


      System.out.println(obtainAttribute(currWeatherLocation, "country"));
      
      NodeList currWeatherCondition = doc.getElementsByTagNameNS("https://your domain.com/ns/rss/1.0", "condition");
      
      System.out.println(obtainAttribute(currWeatherCondition, "date"));
      
      String data = doc.getElementsByTagName("description")
                      .item(1)
                      .getTextContent();

      System.out.println(data);

  }
  
   private static String obtainAttribute(NodeList nodeList, String attribute) {
      String attr = nodeList
              .item(0)
              .getAttributes()
              .getNamedItem(attribute)
              .getNodeValue()
              .toString();
      return attr;
  
  }
}



PreviousNext

Related