You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Jsoup中通过嵌套div ID抓取特定菜单组的元素

解决Jsoup抓取指定菜单组菜谱数据的方案

核心思路

先定位到标题匹配目标菜单组的menu_group_heading元素,再找到其所属card对应的card-body容器,最后提取其中的row recipe_container数据。

实现代码

final String TARGET_MENU = "Olive Garden";
final Document doc = Jsoup.connect(pageUrl).get();

// 遍历所有菜单标题元素
for (Element heading : doc.select("div[id*=menu_group_heading]")) {
    String menuName = heading.text().trim();
    // 判断是否为目标菜单组
    if (TARGET_MENU.equals(menuName)) {
        // 定位到标题所属card对应的card-body(适配常见的card结构:card-header -> card-body)
        Element cardBody = heading.parent().nextElementSibling();
        // 提取card-body下所有的菜谱容器
        Elements recipes = cardBody.select("div.row.recipe_container");
        
        // 遍历输出菜谱数据(按需调整字段提取逻辑)
        for (Element recipe : recipes) {
            String recipeTitle = recipe.select(".recipe-title").text();
            String recipeIngredients = recipe.select(".recipe-ingredients").text();
            System.out.printf("菜谱:%s | 配料:%s%n", recipeTitle, recipeIngredients);
        }
        // 找到目标后跳出循环,避免无效遍历
        break;
    }
}

代码说明

  • heading.parent():获取菜单标题所在的card-header容器(因为menu_group_heading是card-header的子元素)。
  • nextElementSibling():获取card-header的下一个同级元素,即对应的card-body(需确保网页结构中两者是相邻同级)。
  • 如果网页结构中card-header和card-body同属一个父级card容器,也可以用更兼容的写法定位card-body:
    Element cardBody = heading.closest(".card").select(".card-body").first();
    

注意事项

  • 用trim()处理菜单名称,避免前后空格导致匹配失败。
  • 菜谱字段的选择器(如.recipe-title)需要根据网页实际的HTML结构调整。

内容的提问来源于stack exchange,提问作者Andrew Estorton

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 01:15:46