Mohan Pandian
Mohan Pandian

Reputation: 11

switch_to_alert.text() not working

I'm using selenium webdriver in python to scrape the content of a popup window. I used driver.switch_to_alert.text() to retrieve the content.

I am getting the alert object when i call driver.switch_to_alert but i'm not able to use acccept(), dismiss() and text function of the object.

if i call alert i get the object <selenium.webdriver.common.alert.Alert at 0x438fbe0>

but if call alert.text i get the following error

NoAlertPresentException                   
Traceback (most recent call last)
<ipython-input-162-7b8c4cd45721> in <module>()
----> 1 alert.text
C:\Users\\Anaconda\lib\site-packages\selenium\webdriver\common\alert.pyc in text(self)
     63         Gets the text of the Alert.
     64         """
---> 65         return self.driver.execute(Command.GET_ALERT_TEXT)["value"]
     66 
     67     def dismiss(self):

I have tried delaying the execution by sleep(5) but nothing works.

Upvotes: 1

Views: 1705

Answers (1)

alecxe
alecxe

Reputation: 474141

Wait for the alert to be present and then switch to it:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException

wait = WebDriverWait(driver, 10)
wait.until(EC.alert_is_present())

alert = driver.switch_to.alert
alert.accept()

Upvotes: 3

Related Questions