Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I want to read the text from the alert box.

If this text is found in the alert box I have to close the alert box:

Alert Box

like image 360
venkat Avatar asked Nov 02 '17 11:11

venkat


2 Answers

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 text
alert.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 text
    alert.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 WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    # other lines of code
    alert = WebDriverWait(driver, 5).until(EC.alert_is_present)
    alert_text = alert.text
    # validate the alert text
    alert.accept()
    

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

like image 134
undetected Selenium Avatar answered Sep 28 '22 13:09

undetected Selenium


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()
like image 45
Ratmir Asanov Avatar answered Sep 28 '22 11:09

Ratmir Asanov