【问题标题】:Extracting HTML element with Java and XPath使用 Java 和 XPath 提取 HTML 元素
【发布时间】:2015-06-29 15:52:58
【问题描述】:

我正在尝试提取地址的纬度和经度。这是代码。

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 并尝试实现它的纬度,但它一直给我 0 节点。getLength();但是,它适用于经度。 如果我想保留 HTML 元素并在 XPath 中使用它,代码应该如何更改?

【问题讨论】:

  • 如果您正在处理 HTML,我会建议 jsoup。 xpath 对于解析 HTML 来说并不是一个好主意。

标签: java html xml xpath web-scraping


【解决方案1】:

您的代码中的这一行似乎有错误:

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

不应该是这样吗?

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

【讨论】:

  • 是的,expr = xpath.compile("//geometry/location/lat");可以做到但我正在寻找任何可以使用的方法 //*[@id=\"collapsible6\"]/div[1]/div[2]/div[1]/span[2] 当我复制这个当我检查 HTML 元素而不是 HTML 源代码时
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-03-05
  • 1970-01-01
  • 1970-01-01
  • 2021-05-02
  • 1970-01-01
  • 2013-08-10
  • 1970-01-01
相关资源
最近更新 更多