Home > Back-end >  Why do I get NoSuchElement error when I have a exception in place?
Why do I get NoSuchElement error when I have a exception in place?

Time:04-11

I have this could which should check if a iframe is available and swithes to it. Then I have this piece of code that check if a certain element is present.

WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH, '//*[@id="stageFrame"]'))) 
try:
    WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.XPATH, '//*[@id="home_video_js"]')))
except NoSuchElementException:
    print("No video located")

I'm not sure why I still get the error:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="stageFrame"]"}

Probably I'm missing something important but I don't know.

CodePudding user response:

First of all the line of code for frame switching is out of the scope of the try-except{} block. So it is never handled.

Next, as you have used WebDriverWait on failure it should return TimeoutException

Finally, as you are switching to an iframe using the id attribute to be more canonical you may like to add the TAG_NAME as well i.e. iframe . So effective code block will be:

try:
    WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH, '//iframe[@id="stageFrame"]'))) 
    WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.XPATH, '//*[@id="home_video_js"]')))
except TimeoutException:
    print("No iframe/video located")
  • Related