尝试运行while循环直到元素可见,然后单击该元素

时间:2019-06-19 03:06:06

标签: python loops selenium while-loop

我需要获取while循环,以在元素可见后继续,然后单击该元素。

使用预期条件进行了尝试,但是我是菜鸟,所以我可能做错了什么。

# wait until apply clickable
apply = wait(driver,10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "body > associate > div > adjust-schedule > div > list-adjustments > div > basecard > div:nth-child(3) > div > fieldset > div > table.table.table-striped > tbody > tr:nth-child(1) > td:nth-child(6) > button")))

while True:
     try:
         apply = driver.find_element_by_css_selector("body > associate > div > adjust-schedule > div > list-adjustments > div > basecard > div:nth-child(3) > div > fieldset > div > table.table.table-striped > tbody > tr:nth-child(1) > td:nth-child(6) > button")
         apply.click()
     except:
         ignored_exceptions = (NoSuchElementException, StaleElementReferenceException,)
         clckfilter = wait(driver, 10, ignored_exceptions=NoSuchElementException)\
             .until(EC.presence_of_element_located((By.XPATH, "/html/body/associate/div/adjust-schedule/div/list-adjustments/div/basecard/div[2]/div/fieldset/div/table[1]/thead/tr/th[4]/button")))
         clckfilter.click()
         apply.click()
         driver.find_element_by_css_selector("body > associate > div > adjust-schedule > div > list-adjustments > div > basecard > div:nth-child(3) > div > fieldset > div > table.table.table-striped > tbody > tr:nth-child(1) > td:nth-child(6) > div > button.btn.btn-primary").click()
     # if: EC.presence_of_element_located(By.CSS_SELECTOR, "body > associate > div > adjust-schedule > div > list-adjustments > div > basecard > div:nth-child(3) > div > fieldset > div > table.table.table-striped > tbody > tr:nth-child(1) > td:nth-child(6) > button"): continue

如果我删除了apply.click和下一行,该程序将按照我的需要进行循环,但是在应用按钮可见之前,我无法弄清楚如何使其循环。 (一旦我的班次轮班,它就会变得可见)

1 个答案:

答案 0 :(得分:0)

尝试一下:

def click():
try:
    wait = WebDriverWait(self.browser, 15)
    wait.until(EC.visibility_of_element_located(“selector”))
    driver.find_element_by_css_selector(“selector”).click()
except:
    Click()

在上面的代码中,我创建了一个单独的方法来单击“尝试”中的该元素,我编写了用于单击该元素的代码,并且如果该元素不可见(除了除外),则再次调用同一方法直到该元素可见。