Click a button in loop unless a new element gets added to the source of page - python selenium

Viewed 25

I'm struggling to make code like: click the button with the help of the selenium unless a new table get created and stop after the table exists. I'm using python with selenium. i've tried to search everywhere but didn't find the solution. any help will be appreciated.

my code

while not driver.find_element(By.ID("tableID")):
    submit_btn.click()
1 Answers

Change find_element with find_elements.
find_element will throw exception in case of no element exists while find_elements returns a list of web elements matching the passed locator. In case of matching elements existing it will return a non-empty list interpreted by Python as a Boolean True. Otherwise it will return an empty list interpreted by Python as a Boolean False.
Also you have a syntax problem in (By.ID("tableID")).
This should work:

while not driver.find_elements(By.ID, "tableID"):
    submit_btn.click()

Also you may wish to put some delay inside the loop to not perform clicks too fast, so this may be better:

while not driver.find_elements(By.ID, "tableID"):
    submit_btn.click()
    time.sleep(0.1)
Related