Hot to capture Selenium WebDriver exception using Python Interactive Window in Visual Studio Code?

Question:

I receive the Selenium exception NoSuchElementException though I have a try except block.
Here is a reduced version of the code, the stack trace indicates that it is the WebDriverWait line that is causing the Exception:

from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.common.exceptions import (TimeoutException,NoSuchElementException)

driver = webdriver.Chrome('chromedriver.exe')
driver.get("https://example.com")

all_rows = []
for row in all_rows:
    row.find_element(By.XPATH, './/td[3]').click()
    try:
        WebDriverWait(driver, 2).until(EC.presence_of_element_located((By.XPATH, "//button[text() = 'Close']")))
        # wait.until(EC.element_to_be_clickable((By.XPATH, "//button[text() = 'Close']")))
    except Exception as e:
        print(e)


In debugging options under ‘Breakpoints’, ‘Raised Exceptions’ is unticked.

Asked By: lazarus

||

Answers:

Accordingly to presented here code, the exception can be cause by row.find_element(By.XPATH, './/td[3]').click() code line.
This line is not inside the try block now.
If so, you can simply move it into the try block, as following:

from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.common.exceptions import (TimeoutException,NoSuchElementException)

driver = webdriver.Chrome('chromedriver.exe')
driver.get("https://example.com")

all_rows = []
for row in all_rows:    
    try:
        row.find_element(By.XPATH, './/td[3]').click()
        WebDriverWait(driver, 2).until(EC.presence_of_element_located((By.XPATH, "//button[text() = 'Close']")))
        # wait.until(EC.element_to_be_clickable((By.XPATH, "//button[text() = 'Close']")))
    except Exception as e:
        print(e)

Answered By: Prophet