2016-03-16 42 views
0

我使用jsoup製作用java履帶,問題是,我爬行網站並非所有的網頁都可能在谷歌顯示了一個地址地圖,我的程序失敗,當我嘗試從谷歌地圖得到經度和緯度,並且頁面沒有這個元素aviv。Jsoup拋出一個異常時,它沒有找到的HTML元素

我做一個簡單的檢查,如果有html元素

if(!doc.getElementsByTag("noscript").first().select("img").attr("src").isEmpty()){ 

,這就是失敗,雖然應該檢查是否是空元素,以避免控制檯,它拋出一個異常信息的打印。

Exception in thread "main" java.lang.NullPointerException 
    at ewisemapsTest.MetrosCubicosCrawler.crawlLiga(Unknown Source) 
    at ewisemapsTest.MetrosCubicosCrawler.crawl(Unknown Source) 
    at ewisemapsTest.MetrosCubicosCrawler.main(Unknown Source) 

它失敗的Java代碼:

if(!doc.getElementsByTag("noscript").first().select("img").attr("src").isEmpty()){ 

          String latLon = doc.getElementsByTag("noscript").first().select("img").attr("src"); 


          int inicio = latLon.indexOf("=")+1; 
          int medio = latLon.indexOf("%"); 
          int fin = latLon.indexOf("&"); 

          String lat = latLon.substring(inicio, medio); 
          String lon = latLon.substring((medio+3), fin); 
          System.out.println("\nCoordenadas lat:"+lat +" lon: " + lon); 
          } 

什麼,我在這裏失蹤?

回答

4

first()返回null如果設置爲空。在繼續之前,您需要驗證它不是。

Element element = doc.getElementsByTag("noscript").first(); 
if (element != null && !element.select("img").attr("src").isEmpty()) 
{ 
} 

請注意,您應該仔細檢查您正在調用的其他方法,並確保正確處理其「失敗」情況。有些人可能會將空列表轉換爲空列表,但其他人可能不會。

+0

這個明顯更好的解決方案! –

相關問題