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

三世轮回 提交于 2019-11-29 15:05:40

问题


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?


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/30963705/python-regex-attributeerror-nonetype-object-has-no-attribute-group

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!