NoneType in python

前端 未结 2 1769
梦毁少年i
梦毁少年i 2021-01-29 10:03

I was trying to get some rating data from Tripadvisor but as i was trying to fetch the data i was getting

\'NoneType\' object is not subscriptable

2条回答
  •  误落风尘
    2021-01-29 10:37

    It means that not all divs with a class of rating have images with an alt attribute. You should handle this appropriately - to ignore such cases, just wrap your print (rate.img['alt']) in a try, except block, or check to see if rate.img is None first.

    First option:

    try:
        print(rate.img['alt'])
    except TypeError:
        print('Rating error')
    

    Second option:

    for rate in soup.find_all('div',{"class":"rating"}):
        if rate.img is not None:
            print (rate.img['alt'])
    

    The first option follows EAFP (Easier to ask for forgiveness than permission), a common Python coding style, whereas the second follows LBYL (Look before you leap). In this case, I would suggest the second.

提交回复
热议问题