Web scraping often involves unpredictable scenarios. Proper error handling ensures scripts don’t break unexpectedly.
Try-except in Python is used to catch and handle exceptions (errors) that occur during execution. If the code in the try block runs normally, then it’s business as usual. However, if an error occurs, the except block runs instead, which prevents the entire script from crashing.
Now in 99% of cases, you’re going to want to close the pop-up, but we want to be thorough, so let’s first look at how to switch to a pop-up window.
try:
element = driver.find_element(By.ID, 'target-element')
element.click()
except Exception as e:
print(f"Error encountered: {e}")
In this case, the except code prints a message.
We covered explicit waits in the previous module for navigation, but they're also a handy means of Selenium error handling.
A common error you may come across is ElementNotInteractableException. In plain English, the element isn’t clickable. This either means you’ve made an error in your code, and are targeting the wrong element or you’re simply too quick - the element isn’t in a clickable state when the code is executed.
And this is where explicit waits can help. If you’re getting this error, set a wait and see if the results improve.
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
wait = WebDriverWait(driver, 10)
try:
element = wait.until(EC.element_to_be_clickable((By.ID, 'target-element')))
element.click()
except Exception as e:
print(f"Error: {e}")
Finally, let’s round this module off with some other error messages that you may come across.
Our community is here to support your growth, so why wait? Join now and let’s build together!