Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 735
P A N Avatar asked Jun 21 '15 10:06

P A N


2 Answers

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)
like image 110
P A N Avatar answered Sep 19 '22 10:09

P A N


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:
    # ...
like image 21
Maroun Avatar answered Sep 21 '22 10:09

Maroun