Python regex AttributeError: NoneType object has no attribute group

Python regex AttributeError: NoneType object has no attribute group

I managed to figure out this solution: omit group() for the situation where the searchbox reply is No results and thus doesnt match the Regex.

try:
    searchbox_result = re.match(^.*(?=(()), searchbox).group()
except AttributeError:
    searchbox_result = re.match(^.*(?=(()), searchbox)

When you do

re.match(^.*(?=(()), search_result.text)

then if no match was found, None will be returned:

Return None if the string does not match the pattern; note that this is different from a zero-length match.

You should check that you got a result before you apply group on it:

res = re.match(^.*(?=(()), search_result.text)
if res:
    # ...

Python regex AttributeError: NoneType object has no attribute group

This error occurs due to your regular expression doesnt match your targeted value. Make sure whether you use the right form of a regular expression or use a try-catch block to prevent that error.

try:
    pattern = r^.*(?=(())
    searchbox_result = re.match(pattern, searchbox).group()
except AttributeError:
    print(cant make a group)

Thank you

Leave a Reply

Your email address will not be published. Required fields are marked *