Skip to content
Advertisement

Why is it saying my variable is not subscriptable?

I sometimes get this error (TypeError: ‘NoneType’ object is not subscriptable) when I call getLink()[0], and I sometimes don’t. Does anyone know why I’m getting this error? getLink() should be subscriptable…

def getLink():
        for link in getElements():
            if "orgs" in link:
                return ['orgs', link]
            elif "pac" in link and "summary" in link:
                return ['pac', link]
            elif "federal-lobbying" in link and "summary" in link:
                return ['fl', link]
            else:
                return 'error'

    # get elements
    if getLink()[0] == "orgs":

EDIT: my issue was I needed a longer time.sleep() waiting function to give my page time to load to feed data into getElements(), sometimes it loaded fast enough and sometimes not. Thanks all!

Advertisement

Answer

This will work fine:

def getLink():
        elements = getElements()
        if not elements:
                return ["error"]

        for link in elements:
            if "orgs" in link:
                return ['orgs', link]
            elif "pac" in link and "summary" in link:
                return ['pac', link]
            elif "federal-lobbying" in link and "summary" in link:
                return ['fl', link]
            else:
                return ['error']
link = getLink()
# get elements
if link[0] == "orgs":

as CherryDT Explained the issue is with getElements() if getElements() returns None then your getLink() function also returns None to solve this you will have to add a guard that checks what getElements() returns

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement