Python regex AttributeError: object 'NoneType' does not have attribute 'group'

I am using Regex to extract specific content from a search box on a web page using selenium.webDriver .

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

The code runs as long as the search field returns results matching Regex. But if the search box responds with the string "No results" , I get an error:

AttributeError: the NoneType object does not have a group attribute

How can I get the script to handle the "No results" situation?

+5
source share
2 answers

I managed to find out this solution, it is related to neglecting group() for the situation when the answer in the search string is "No results" and, therefore, does not match Regex.

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

or simply:

 try: searchbox_result = re.match("^.*(?=(\())", searchbox.group() except: searchbox_result = None 
+6
source

When you do

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

then if no match is found, None returned:

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

You must ensure that you have a result before applying group to it:

 res = re.match("^.*(?=(\())", search_result.text) if res: # ... 
+3
source

All Articles