Search code examples
pythonpython-3.xdjangodjango-views

expected output is not coming in django


I am trying to scrap the mega menu from the website using python beautiful soup frame work !

for i in menu_items('https://natureshair.com.au/'):
   print(json.dumps(i, indent=6))

The output is fine! I can able to different level of menus !

output

Now i want to see the result in browser so i have used Django framework to display this out put in browser

this is my views.py code

def say_hello(request): 
    for i in menu_items('https://natureshair.com.au/'):
       return HttpResponse(json.dumps(i, indent=6))

But i am getting only first level of menu list in browser ! dont know where i have missed something

browser outout

Please let me know what i am missing here ?


Solution

  • You enumerate over the results, but you return a response from the moment you get the first item. This thus means that it returns the result from that item.

    You thus should first collect all results, and then dump that blob:

    def say_hello(request):
        results = list(menu_items('https://natureshair.com.au/'))
        return JsonResponse({'results': results})

    or for two websites:

    def say_hello(request):
        results = list(
            item
            for link in ('https://natureshair.com.au/', 'https://www.google.com/')
            for item in menu_items(link)
        )
        return JsonResponse({'results': results})