gpt4 book ai didi

java - Jsoup找不到html元素时抛出异常

转载 作者:行者123 更新时间:2023-12-01 18:06:31 27 4
gpt4 key购买 nike

我正在使用jsoup用java制作一个爬虫,问题是我正在爬行的网站并非所有页面都有可以在谷歌地图中显示的地址,当我尝试获取纬度时我的程序失败了来自谷歌地图的经度,并且该页面没有可用的此元素。

我简单检查是否存在 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())
{
}

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

关于java - Jsoup找不到html元素时抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36048750/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com