I'm trying to make a loop with selenium that searches for element with class name "buy-button" and if it doesn't find it to refresh and repeat until it finds the button. This is the code I currently have but it doesn't work. I'm getting an error code that it can't find the element which makes sense because it isn't there yet.
buyButton = driver.find_element(By.CLASS_NAME, "buy-button")
while not (driver.find_element(By.CLASS_NAME, "buy-button")):
time.sleep(1)
driver.refresh()
buyButton.click()
The error code
Traceback (most recent call last):
, line 12, in <module> driver.find_element(By.CLASS_NAME, "buy-button")
line 1244, in find_elementreturn self.execute(Command.FIND_ELEMENT, {
Thanks in advance
CodePudding user response:
driver.find_element
method returns web element in case it was found. Otherwise it throws exception, not a Boolean False
as you could think.
In order to make your code work as you want you should use driver.find_elements
method.
It returns a list of found web elements.
In case element is found it will return a non-empty list which is interpreted as a Boolean True
by Python. In case no elements found it will return an empty list which is interpreted by Python as a Boolean True
.
So, your code can be as following:
buyButton = driver.find_elements(By.CLASS_NAME, "buy-button")
while not (driver.find_elements(By.CLASS_NAME, "buy-button")):
time.sleep(1)
driver.refresh()
buyButton[0].click()
CodePudding user response:
With selenium, if you try to find an element that doesn't exist on the page and it doesn't exist then an error will be raised. If you want to keep executing afterwards then you will need to use try except
. Something like this would work:
while True:
try:
buyButton = driver.find_element(By.CLASS_NAME,"buy-button")
break
except:
time.sleep(1)
driver.refresh()
buyButton.click()
Though if the element doesn't exist on the page you are on, refreshing will not help at all.
CodePudding user response:
I think you should use a wait conditioned to the visibility of your component like in the example bellow:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Firefox()
driver.get("http://somedomain/url_that_delays_loading")
try:
element = WebDriverWait(driver, 10).until(
EC.visibility_of_element_located((By.ID, "myDynamicElement"))
)
finally:
driver.quit()
The visibility_of_element_located function in the example waits 10 seconds to check if the component is visible. You can check selenium waits for more examples and types of coditional waits.