简体   繁体   中英

Why is the code throwing "AttributeError: 'NoneType' object has no attribute 'group'"?

I tried to run my code however it is throwing "AttributeError: 'NoneType' object has no attribute 'group'" and I can't seem to install regex. I read that it is built-in but I dont know what to do. here is the code that throws the error:

while i>0:
    print("Number "+str(i))
    src = str(br.parsed())
    start1 ="¿"
    end1 = "?<"
    result = re.search('%s(.*)%s' % (start1,end1), src).group(1) 
    print(str(result))
    question_index=questions.index(result)
    print("The answer is " + answers[question_index])
    question_form = br.get_form()
    question_form["user_answer"]=answers[question_index]
    br.submit_form(question_form)
    i=i-1 

this line throws the error:

result = re.search('%s(.*)%s' % (start1,end1), src).group(1)

You don't need to "install" the regex module re . You are correct that it is built-in, you do have it, and it is working fine. If you didn't have it, you would have gotten an ImportError when you tried to import it.

The problem is that your regex search is not finding any matches, so it is returning None . Then you're immediately trying to access the attribute "group" in None on the same line, which doesn't exist. Separate out the search from .group(1) , check the return type for None , and proceed only if the return is not None . If the return value of re.search() is None , then do whatever you want to handle the error - exit, display error message, HCF , whatever.

Change this:

result = re.search('%s(.*)%s' % (start1,end1), src).group(1)

To something like this:

result = re.search('%s(.*)%s' % (start1,end1), src)
if result is None:
    print("Error! No matches")
    return # or break, exit, throw exception, whatever

result = result.group(1) # reassign just the group you want to "result"
# carry on with the rest of your loop

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM