How to read the text from the alert box using Python + Selenium How to read the text from the alert box using Python + Selenium selenium selenium

How to read the text from the alert box using Python + Selenium


To read the text from the Alert Box, validate and close the Alert you have to switch to the Alert first and follow the below mentioned steps:

alert = chrome.switch_to_alert()alert_text = alert.text# validate the alert textalert.accept()

However, now it seems switch_to_alert() is deprecated. So as per the current implementation you need to use:

  • switch_to.alert() as follows:

    alert = driver.switch_to.alert()alert_text = alert.text# validate the alert textalert.accept()
  • As per best practices you should always induce WebDriverWait for the alert_is_present() before switching to an Alert as follows:

    from selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support import expected_conditions as EC# other lines of codealert = WebDriverWait(driver, 5).until(EC.alert_is_present)alert_text = alert.text# validate the alert textalert.accept()

You can find a relevant discussion in Why switching to alert through selenium is not stable?


First of all, you should switch to the alert window:

alert = driver.switch_to_alert()

Then get the text on the alert window by using alert.text. And check your text for correctness.

Then do such action (close the alert window):

alert.accept()


I have similar situations as this in my framework as well, and this is how I solved it.

if (_driver.FindElement(By.XPath("//*[text()[contains(.,'No Sales Found')]")).Enabled){     //Do Something}

Put this after functionality that may bring the error up. Also, this example is using C# and _driver as the driver, which may be different from what you are using.