Python 正则表达式 AttributeError : 'NoneType' object has no attribute 'group'

标签 python regex attributeerror

我使用正则表达式从网页上的搜索框中检索某些内容,并使用 selenium.webDriver

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

只要搜索框返回与正则表达式匹配的结果,代码就可以正常工作。但是如果搜索框回复字符串 "No results" 我会得到错误:

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

如何让脚本处理“无结果”情况?

最佳答案

我想出了这个解决方案:在搜索框回复为“无结果” 并因此与正则表达式不匹配的情况下省略 group()

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

关于Python 正则表达式 AttributeError : 'NoneType' object has no attribute 'group' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30963705/

相关文章:

Python:无法从导入的模块调用方法

php - 在 RegEx (PCRE) 中的上一场比赛结束时继续

python - 根据条件在 Pandas 数据框中迭代并分配值

if else 语句上的 python 3.5.1 语法错误

python - 将文本文件解析为字典列表

java - 在文本中查找 ASCII "arrows"

java - 正则表达式:int 不能取消引用

python - AttributeError : 'module' object has no attribute

python - Flake8Lint 错误 : AttributeError: 'NoneType' object has no attribute 'kind'

Python Selenium - 属性错误 : WebElement object has no attribute sendKeys