使用JSoup爬取网页列表项时for循环仅返回第一条数据如何解决
问题分析
- 外层循环逻辑错误:你选择的
section.recipe__ingredients.col-12.mt-md.col-lg-6在目标页面中仅存在1个,所以外层for循环只会执行1次,本身无法遍历多条食材条目。 - 缺少内层遍历逻辑:你没有对食材区域下的所有li元素做循环遍历,仅通过单次
nth-of-type规则取元素,自然只能拿到1条数据。 - 变量逻辑错误:每次进入外层循环都会把计数变量row重置为0,且单次循环内连续执行两次
row++,计数逻辑完全混乱。
修正后代码
import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.IOException; public class WebScrape { public static void main(String[] args) { scrapeBBC("https://www.bbcgoodfood.com/recipes/spanish-omelette"); } static void scrapeBBC(String url){ try{ Document recipe = Jsoup.connect(url).get(); // 直接获取唯一的食材区域元素 Element ingredientSection = recipe.selectFirst("section.recipe__ingredients.col-12.mt-md.col-lg-6"); if (ingredientSection == null) { System.out.println("未匹配到食材区域"); return; } // 选中食材区域下所有的食材列表项 Elements ingredientItems = ingredientSection.select("li.list-item--separator.list-item.pt-xxs.pb-xxs"); // 遍历所有列表项输出 int row = 1; for (Element item : ingredientItems) { System.out.println(row + ". " + item.text()); row++; } }catch(IOException ioe){ System.out.println("无法连接到目标URL"); ioe.printStackTrace(); } } }
代码说明
- 用
selectFirst直接获取唯一的食材区域元素,去掉无意义的外层循环 - 一次性选中食材区域下全部食材列表项,直接遍历元素集合即可拿到所有食材数据
- 计数变量
row移到循环外初始化,每遍历一条食材计数+1,逻辑清晰 - 增加了食材区域为空的判断,避免空指针异常
内容的提问来源于stack exchange,提问作者Zeroid
相关产品推荐
相关产品推荐

