I want to exception handle 'list index out of range.'

前端 未结 6 901
甜味超标
甜味超标 2020-11-27 12:53

I am using BeautifulSoup and parsing some HTMLs.

I\'m getting a certain data from each HTML (using for loop) and adding that data to a cert

相关标签:
6条回答
  • 2020-11-27 13:38

    For anyone interested in a shorter way:

    gotdata = len(dlist)>1 and dlist[1] or 'null'
    

    But for best performance, I suggest using False instead of 'null', then a one line test will suffice:

    gotdata = len(dlist)>1 and dlist[1]
    
    0 讨论(0)
  • 2020-11-27 13:46

    Handling the exception is the way to go:

    try:
        gotdata = dlist[1]
    except IndexError:
        gotdata = 'null'
    

    Of course you could also check the len() of dlist; but handling the exception is more intuitive.

    0 讨论(0)
  • 2020-11-27 13:49

    Taking reference of ThiefMaster♦ sometimes we get an error with value given as '\n' or null and perform for that required to handle ValueError:

    Handling the exception is the way to go

    try:
        gotdata = dlist[1]
    except (IndexError, ValueError):
        gotdata = 'null'
    
    0 讨论(0)
  • 2020-11-27 13:50
    for i in range (1, len(list))
        try:
            print (list[i])
    
        except ValueError:
            print("Error Value.")
        except indexError:
            print("Erorr index")
        except :
            print('error ')
    
    0 讨论(0)
  • 2020-11-27 13:56

    You have two options; either handle the exception or test the length:

    if len(dlist) > 1:
        newlist.append(dlist[1])
        continue
    

    or

    try:
        newlist.append(dlist[1])
    except IndexError:
        pass
    continue
    

    Use the first if there often is no second item, the second if there sometimes is no second item.

    0 讨论(0)
  • 2020-11-27 13:56

    A ternary will suffice. change:

    gotdata = dlist[1]
    

    to

    gotdata = dlist[1] if len(dlist) > 1 else 'null'
    

    this is a shorter way of expressing

    if len(dlist) > 1:
        gotdata = dlist[1]
    else: 
        gotdata = 'null'
    
    0 讨论(0)
提交回复
热议问题