我试图在未显示 xpath 时停止 while 循环。但是,代码以 NoSuchElementException
消息停止。这是我的代码,
n=1
while n<100:
n+=1
time.sleep(10)
#
Data=driver.find_element_by_xpath('.//tbody//tr//td//span//a[text() != ""]').is_displayed()
if Data == True:
...
if Data == False:
break
但我得到:
"NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":".//tbody//tr//td//span//a[text() != ""]"}"
这正是我想要停止循环的时候……当元素不可定位时。
最佳答案
使用 try
block 并从 selenium
导入异常。
from selenium.common.exceptions import NoSuchElementException
...
while n<100:
...
try:
Data=driver.find_element_by_xpath('.//tbody//tr//td//span//a[text() != ""]').is_displayed()
except NoSuchElementException:
break
... rest of code ...
关于python - 当 xpath = 没有这样的元素时停止循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54466471/