Python 正则表达式 AttributeError: 'NoneType' 对象没有属性 'group'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30963705/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python regex AttributeError: 'NoneType' object has no attribute 'group'
提问by Winterflags
I use Regex to retrieve certain content from a search box on a webpage with selenium.webDriver.
我使用正则表达式从网页上的搜索框中检索某些内容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:
只要搜索框返回与正则表达式匹配的结果,代码就可以工作。但是如果搜索框回复字符串"No results"我得到错误:
AttributeError: 'NoneType' object has no attribute 'group'
AttributeError: 'NoneType' 对象没有属性 'group'
How can I make the script handle the "No results"situation?
我怎样才能让脚本处理这种"No results"情况?
采纳答案by Winterflags
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.
我设法找出了这个解决方案,它与忽略group()搜索框回复"No results"因此与正则表达式不匹配的情况有关。
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
回答by Maroun
When you do
当你做
re.match("^.*(?=(\())", search_result.text)
then if no match was found, Nonewill be returned:
然后如果没有找到匹配项,None将返回:
Return
Noneif the string does not match the pattern; note that this is different from a zero-length match.
None如果字符串与模式不匹配,则返回;请注意,这与零长度匹配不同。
You should check that you got a result before you apply groupon it:
在申请之前,您应该检查是否获得了结果group:
res = re.match("^.*(?=(\())", search_result.text)
if res:
# ...

![python socket.error: [Errno 98] 地址已被使用](/res/img/loading.gif)