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

P A N picture P A N · Jun 21, 2015 · Viewed 74.2k times · Source

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?

Answer

P A N picture P A N · Jun 21, 2015

I managed to figure out this solution, it had to do with neglecting 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)

or simply:

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