Handle Alert in Selenium Python

Profile picture for user arilio666

In Selenium Python, alerts can be handled using the Alert method. Here's an example:

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.alert import Alert

driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))

driver.maximize_window()
driver.get('http://autopract.com/selenium/alert5/')

driver.find_element(By.ID, 'alert-button').click()
alert = Alert(driver)
print(alert.text)
alert.accept()
driver.find_element(By.ID,'confirm-button').click()
alert.dismiss()
  • In this example, we first create a new instance of the Chrome driver and navigate to a web page with an alert. 
  • We then locate a button on the page that triggers the alert and click on it. 
  • We then switch to the alert and text to get its text. 
  • We then use accept to accept the alert and close the browser.
  • You can also dismiss an alert using the dismiss method instead of accept. 
  • Additionally, you can send a text to a prompt alert using the send_keys method