簡體   English   中英

Jsoup在找不到html元素時引發異常

[英]Jsoup throws an exception when it doesn't find the html element

我正在使用jsoup用java編寫爬蟲,問題是我要爬網的網站並非所有頁面都有可以在google地圖中顯示的地址,當我嘗試從google獲取經度和緯度時,我的程序失敗地圖和頁面沒有此元素。

我簡單檢查一下是否有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); 
                          }

我在這里想念的是什么?

如果集合為空,則first()返回null 您需要先驗證它是否存在,然后再繼續。

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

請注意,您應仔細檢查正在調用的其他方法,並確保正確處理它們的“失敗”情況。 有些人可能會將一個空列表轉換為一個空列表,但其他人則可能不會。

暫無
暫無

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

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