首页 > 解决方案 > 如何使用“if”用python测试网页中元素的存在?

问题描述

我创建了一个循环(while True)来使用 python 自动执行站点上的任务。此代码单击两个字段,直到页面上出现一个元素

(browser.find_element_by_id ('formComp: buttonBack').

当这个元素出现时,我希望循环停止并转到下一个代码块。

我是这样测试的,但它犯了一个错误。"formComp: buttonback"Python 报告找不到该元素。但这就是它,如果没有找到继续循环:

    while (browser.find_element_by_id('formComp:repeatCompromissoLista:0:tableRealizacao:0:subtableVinculacoes:0:vinculacao_input')):
        vinc = wait.until(EC.presence_of_element_located((By.ID, 'formComp:repeatCompromissoLista:0:tableRealizacao:0:subtableVinculacoes:0:vinculacao_input')))
        vinc = browser.find_element_by_id('formComp:repeatCompromissoLista:0:tableRealizacao:0:subtableVinculacoes:0:vinculacao_input')
        vinc.send_keys('400')
        enterElem5 = wait.until(EC.element_to_be_clickable((By.ID, 'formComp:buttonConfirmar')))
        enterElem5 = browser.find_element_by_id('formComp:buttonConfirmar')
        enterElem5.send_keys(Keys.ENTER)
        time.sleep(int(segundosv))
        if (browser.find_element_by_id('formComp:buttonRetornar')== True):
            break
        else:
            continue

标签: python-3.xseleniumselenium-webdriver

解决方案


尝试这样希望这会有所帮助length。检查按钮的计数是否超过 0。

if (len(browser.find_elements_by_id('formComp:buttonRetornar'))>0):
        break
else:
        continue

推荐阅读