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:
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?
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With