Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Jsoup在不执行时引发异常';找不到html元素_Java_Jsoup - Fatal编程技术网

Java Jsoup在不执行时引发异常';找不到html元素

Java Jsoup在不执行时引发异常';找不到html元素,java,jsoup,Java,Jsoup,我正在使用jsoup用java制作一个爬虫程序,问题是我正在爬虫的站点并非所有页面都有一个可以在google maps中显示的地址,当我试图从google maps中获取纬度和经度时,我的程序失败,并且页面没有这个元素 我简单地检查是否有html元素 if( !doc.getElementsByTag("noscript").first().select("img").attr("src").isEmpty()){ 这就是它失败的地方,尽管它应该检查元素是否为空,以避免在控制台上打印它引

我正在使用jsoup用java制作一个爬虫程序,问题是我正在爬虫的站点并非所有页面都有一个可以在google maps中显示的地址,当我试图从google maps中获取纬度和经度时,我的程序失败,并且页面没有这个元素

我简单地检查是否有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())
{
}
注意:您应该仔细检查正在调用的其他方法,并确保正确处理它们的“失败”情况。有些可能会将空列表转换为空列表,但其他可能不会。

first()
如果集合为空,则返回
null
。在继续之前,您需要验证它是否正确

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

注意:您应该仔细检查正在调用的其他方法,并确保正确处理它们的“失败”情况。有些人可能会将空列表转换为空列表,但其他人可能不会。

这显然是更好的解决方案!这显然是更好的解决方案!