Python regex AttributeError: 'NoneType' object has no attribute 'group'
Asked Answered
C

3

26

I use Regex to retrieve certain content from a search box on a webpage with selenium.webDriver.

searchbox = driver.find_element_by_class_name("searchbox")
searchbox_result = re.match(r"^.*(?=(\())", searchbox).group()

The code works as long as the search box returns results that match the Regex. But if the search box replies with the string "No results" I get error:

AttributeError: 'NoneType' object has no attribute 'group'

How can I make the script handle the "No results" situation?

Caudell answered 21/6, 2015 at 10:53 Comment(0)
C
30

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

try:
    searchbox_result = re.match("^.*(?=(\())", searchbox).group()
except AttributeError:
    searchbox_result = re.match("^.*(?=(\())", searchbox)
Caudell answered 21/6, 2015 at 11:33 Comment(2)
Is there any solution if I have multiple number of regexes and dont want to except them individually?Circumscissile
In your code ) is missing after searchbox or after group()Welloiled
B
14

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:
    # ...
Banger answered 21/6, 2015 at 10:55 Comment(6)
Thanks, can you give a more specific example of code? I basically want it to write "" to res if it finds nothing. Or alternatively, pass if using except.Caudell
@Winterflags You can check res is None, if it is, change it to "".Banger
@Winterflags Also note that your regex is greedy, it matches "abc(def" in the following string abc(def(. Is that what you want?Banger
I updated the question with if condition and traceback. It seems to refer back to the line with re.match even though I do if after regex.Caudell
The regex works as intended right now, perhaps overly greedy but it doesn't produce capture errors. If it's necessary to change it to account for None we can do that.Caudell
@Winterflags You should check that the assigned object is not None: if name is None.Banger
A
0

This error occurs due to your regular expression doesn't 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("can't make a group")

Thank you

Airtoair answered 23/10, 2021 at 9:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.