I’m trying to add a condition to my code to check if a HTML element (<section class="pv-contact-info__contact-type ci-phone">) exists, and if it does not, write Phone numb not available for this provider to a CSV file. I have written the following code but am getting a selenium.common.exceptions.TimeoutException error:
try:
phone_element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//section[@class='pv-contact-info__contact-type ci-phone']//span[@class='t-14 t-black t-normal']")))
phone = phone_element.get_attribute("innerHTML").strip()
except NoSuchElementException:
phone = "Phone numb not available for this provider"
The issue is that you are catching a NoSuchElementException exception, but the actual exception being raised is a TimeoutException. To fix this issue, you need to catch the correct exception.
Here’s the updated code:
from selenium.common.exceptions import TimeoutException
try:
phone_element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//section[@class='pv-contact-info__contact-type ci-phone']//span[@class='t-14 t-black t-normal']")))
phone = phone_element.get_attribute("innerHTML").strip()
except TimeoutException:
phone = "Phone number not available for this provider"
By importing TimeoutException from selenium.common.exceptions, you can catch the correct exception when the element is not found within the specified timeout.