python - 当 xpath = 没有这样的元素时停止循环

标签 python selenium for-loop while-loop

我试图在未显示 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/

相关文章:

python - 从操作中排除列而不删除它

python - Pandas 嵌套的 groupby 给出了意想不到的结果

python - GdkPixbuf.PixbufDestroyNotify - NotImplementedError - python gtk3

selenium - 由于向后兼容性已被删除,如何使用 ChromeDriver 73 和 Chrome 版本 74 执行现有的 selenium 脚本?

java - 使用 Selenium 生成随机电子邮件

javascript - 通过for循环发送信息

java - Java中将字符串拆分为字符并与用户输入进行匹配

python - 在一段时间后终止 Python 脚本

python - [Selenium][geckodriver] 如何更改 firefox 配置文件首选项字段,如 "security.insecure_field_warning.contextual.enabled"

python - 用 JSON 中的字符串列表替换单词中的多个相等字符串