Python regex AttributeError:"NoneType"对象没有属性"group" [英] Python regex AttributeError: 'NoneType' object has no attribute 'group'
问题描述
我使用正则表达式从具有selenium.webDriver
的网页上的搜索框中检索某些内容.
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()
只要搜索框返回与正则表达式匹配的结果,代码就起作用.但是,如果搜索框用字符串"No results"
答复,则会出现错误:
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'对象没有属性'group'
AttributeError: 'NoneType' object has no attribute 'group'
如何使脚本处理"No results"
情况?
推荐答案
我设法弄清楚了这个解决方案,它与在搜索框回复为"No results"
的情况下忽略group()
有关,因此没有匹配正则表达式.
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)
或简单地:
try:
searchbox_result = re.match("^.*(?=(\())", searchbox.group()
except:
searchbox_result = None
这篇关于Python regex AttributeError:"NoneType"对象没有属性"group"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!