简体   繁体   中英

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?

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)

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:
    # ...

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

Thank you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM