简体   繁体   中英

How to keep clicking element when visible - SELENIUM

I need to keep clicking on element unless it turns invisible.

my code:

 try:
    element = WebDriverWait(self.browser, 10).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='content']//form//div[2]//span[@id='main_content']")))
    if element:
        while element:
            submit.click()
except:
    pass

current code clicks once or none

Your original loop might only click once because element is of type WebElement , not Boolean , so element == True will always return false.

I would change up your code structure a bit, to avoid storing the WebElement in element variable & locate fresh instance each time loop iterates:

from selenium.common.exceptions import TimeoutException


# find your submit button outside loop
submit = driver.find_element_by_xpath("some_locator")

# perform this loop indefinitely until break condition is met
while True:
    try:

        # optional: You may need to locate submit button with each loop iteration
        # submit = driver.find_element_by_xpath("some_locator")

        # attempt to click submit button
        submit.click()

        # check if element is visible -- this will throw TimeoutException if not
        WebDriverWait(self.browser, 10).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='content']//form//div[2]//span[@id='main_content']")))

    except TimeoutException:
        # case: element is no longer visible, so break out of loop
        break

This code runs a while True: loop where it first attempts to click element, then catches any exception & breaks out of loop if exception is thrown. In this case, exception is thrown when button located is no longer visible, which will throw TimeoutException . So once element is no longer visible & TimeoutException gets thrown, code breaks out of loop.

I changed except: to except TimeoutException: because this is the exception WebDriverWait throws when element is invisible. If we just leave except: with no specific exception to catch, then you may end up with a buried StaleElementReferenceException that happens on submit.click() .

I also added some commented-out code to fix the StaleElementReferenceException in the case that submit.click() DOES throw this exception.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM