我使用正则表达式从网页上的搜索框中检索某些内容,并使用 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/