ratata
ratata

Reputation: 1169

Django, sending beautifulsoup parsed html via ajax gives is not JSON serializable error

I am using beautifulsoup to parse html and trying to pass img elements via JsonResponse to the template.

My view:

def spider(request):

    r = requests.get("https://www.google.com.tr/search?q=cizre&biw=1438&bih=802&source=lnms&tbm=isch&sa=X&ved=0ahUKEwiu8any3vLJAhWBkywKHfEbAeoQ_AUICCgD#imgrc=_")

    soup = BeautifulSoup(r.content, "html.parser")

    images = soup.findAll("img")

    imagesDict = {}
    for i in range(len(images)):
        imagesDict[i] = images[i]

    return JsonResponse(imagesDict)

But i am getting this error:

TypeError at /spider/ <img alt="" height="23" onclick="(function(){var text_input_assistant_js='/textinputassistant/11/tr_tia.js';var s = document.createElement('script');s.src = text_input_assistant_js;(document.getElementById('xjsc')|| document.body).appendChild(s);})();" src="/textinputassistant/tia.png" style="padding-top:2px" width="27"/> is not JSON serializable

Upvotes: 1

Views: 138

Answers (1)

Shang Wang
Shang Wang

Reputation: 25549

You cannot do that, because what BeautifulSoup findAll returns is a list of beautiful soup objects, but json can only have plain types. That error in general says "what you are trying to serialize is not in json recognizable format". You can do:

def spider(request):
    r = requests.get("https://www.google.com.tr/search?q=cizre&biw=1438&bih=802&source=lnms&tbm=isch&sa=X&ved=0ahUKEwiu8any3vLJAhWBkywKHfEbAeoQ_AUICCgD#imgrc=_")
    soup = BeautifulSoup(r.content, "html.parser")
    images = soup.findAll("img")
    imagesDict = {}
    for i, image in enumerate(images):
        # convert object to string
        imagesDict[i] = str(image)
    return JsonResponse(imageDict)

Upvotes: 2

Related Questions