I'm trying to automate processes on a webpage that loads frame by frame. I'm trying to set up a try-except
loop which executes only after an element is confirmed present. This is the code I've set up:
from selenium.common.exceptions import NoSuchElementException
while True:
try:
link = driver.find_element_by_xpath(linkAddress)
except NoSuchElementException:
time.sleep(2)
The above code does not work, while the following naive approach does:
time.sleep(2)
link = driver.find_element_by_xpath(linkAddress)
Is there anything missing in the above try-except loop? I've tried various combinations, including using time.sleep() before try
rather than after except
.
Thanks
If one of them is hidden, and Selenium is interacting with that element, then there is a chance that Selenium will not be able to return it. You can try using some other property to locate the element such as CSS Selector or Xpath . Use explicit waits. This will ensure all timeouts happen after the given time.
The answer on your specific question is:
from selenium.common.exceptions import NoSuchElementException
link = None
while not link:
try:
link = driver.find_element_by_xpath(linkAddress)
except NoSuchElementException:
time.sleep(2)
However, there is a better way to wait until element appears on a page: waits
Another way could be.
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
try:
element = WebDriverWait(driver, 2).until(
EC.presence_of_element_located((By.XPATH, linkAddress))
)
except TimeoutException as ex:
print ex.message
Inside the WebDriverWait call, put the driver variable and seconds to wait.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With