如何用Jsoup获取网页中首个带col-sm-1和available-day类的td内容
提取网页日历中第一个可用日期的Jsoup代码修改
原代码(遍历输出所有可用日期)
Document doc = Jsoup.connect("https://dgpci.mai.gov.ro/drpciv-booking/formular/35/vehicleFirstRegistration") .get(); Elements tds = doc.select("table.calendar-table tbody tr td.col-sm-1.available-day"); for (Element e : tds) { System.out.println(e.text()); }
需求
修改代码,仅打印第一个带有col-sm-1和available-day类的td元素对应的日期。
修改方案
方案1:使用selectFirst()直接获取第一个匹配元素(推荐)
selectFirst()方法直接返回选择器匹配的第一个元素,无需遍历所有结果,效率更高,同时增加空值判断避免空指针异常:
Document doc = Jsoup.connect("https://dgpci.mai.gov.ro/drpciv-booking/formular/35/vehicleFirstRegistration") .get(); Element firstAvailableDay = doc.selectFirst("table.calendar-table tbody tr td.col-sm-1.available-day"); if (firstAvailableDay != null) { System.out.println(firstAvailableDay.text()); }
方案2:基于原代码修改,取第一个元素
如果保留原有的select()方法,可通过first()获取结果集中的第一个元素,同时判断集合是否为空:
Document doc = Jsoup.connect("https://dgpci.mai.gov.ro/drpciv-booking/formular/35/vehicleFirstRegistration") .get(); Elements tds = doc.select("table.calendar-table tbody tr td.col-sm-1.available-day"); if (!tds.isEmpty()) { System.out.println(tds.first().text()); }
说明
根据提供的HTML日历结构,第一个符合条件的日期是14,修改后的代码会输出该值。
内容的提问来源于stack exchange,提问作者Alerta Java
相关产品推荐
相关产品推荐

