簡體   English   中英

使用Java和XPath提取HTML元素

[英]Extracting HTML element with Java and XPath

我正在嘗試提取地址的緯度和經度。 這是編碼。

public static void main(String[] args) throws Exception {
   int responseCode = 0;
   String api = "http://maps.googleapis.com/maps/api/geocode/xml?address=9%20Edinburgh%20Place,%20Centrall&sensor=false&components=country:HK&language=en";         

   URL url = new URL(api);

   HttpURLConnection httpConnection = (HttpURLConnection)url.openConnection();
   httpConnection.connect();
   responseCode = httpConnection.getResponseCode();
   if(responseCode == 200) {
       DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();;
       Document document = builder.parse(httpConnection.getInputStream());
       XPathFactory xPathfactory = XPathFactory.newInstance();
       XPath xpath = xPathfactory.newXPath();      
       XPathExpression expr = xpath.compile("/GeocodeResponse/status");
       String status = (String)expr.evaluate(document, XPathConstants.STRING);
      if(status.equals("OK")) {     
          expr = xpath.compile("//*[@id=\"collapsible6\"]/div[1]/div[2]/div[1]/span[2]");
          Object results = expr.evaluate(document, XPathConstants.NODESET);
          NodeList nodes = (NodeList) results; 
          System.out.println(nodes.getLength());

          for (int i = 0; i < nodes.getLength(); i++){
             System.out.println("latitude: " + nodes.item(i).getNodeValue()); 
          }

          expr = xpath.compile("//geometry/location/lng");
          String lng = (String)expr.evaluate(document, XPathConstants.STRING);
          System.out.println("longitude: " + lng);
      } else      
          throw new Exception("Error from the API - response status: "+status);       
  }
}}

我已經通過檢查Web元素復制了xpath並嘗試實現它的緯度,但它一直為我的nodes.getLength()提供0。 但是,它對於經度效果很好。 如果我想保留HTML元素並在XPath中使用它,代碼應如何更改?

您的代碼似乎在這一行上有錯誤:

expr = xpath.compile("//*[@id=\"collapsible6\"]/div[1]/div[2]/div[1]/span[2]");

不是嗎

expr = xpath.compile("//geometry/location/lat");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM