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

Django仅返回一级菜单问题:Beautiful Soup爬取的多级菜单无法完整展示

问题分析与解决方法

你的Django视图函数存在逻辑错误:return语句放在了for循环内部。当循环执行第一次迭代时,函数就会立即返回第一个菜单项的JSON响应,后续的菜单项不会被遍历和返回,因此浏览器只能看到第一级菜单。

修正后的代码

你需要先把所有菜单项收集到一个列表中,再统一返回整个列表的JSON数据:

import json
from django.http import HttpResponse

def say_hello(request):
    all_menu_items = []
    for item in menu_items('https://natureshair.com.au/'):
        all_menu_items.append(item)
    # 指定content_type让浏览器正确识别JSON格式
    return HttpResponse(json.dumps(all_menu_items, indent=6), content_type='application/json')

或者用更简洁的列表推导式写法:

import json
from django.http import HttpResponse

def say_hello(request):
    all_menu_items = list(menu_items('https://natureshair.com.au/'))
    return HttpResponse(json.dumps(all_menu_items, indent=6), content_type='application/json')

这样就能在浏览器中看到完整的各级菜单数据了。

内容的提问来源于stack exchange,提问作者manikanta gowda

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 07:45:56