Your ultimate guide

Handling Alerts using Selenium with Python

Alert in Selenium: An alert in Selenium is a small message box that appears on the screen to give the user some information or notification.







    With the assistance of Selenium, we can execute various tasks within an alert box such as accepting or dismissing it, obtaining alert messages, and sending actions. These actions rely on the use of the class selenium.webdriver.common.alert.Alert(driver).

Selenium alert methods:
  • accept() - This method accepts an alert pop-up.
    • Syntax:
      • alert = Alert(driver)
      • alert.accept()
  • dismiss() - This method dismisses an alert pop-up.
    • Syntax:
      • alert = Alert(driver)
      • alert.dismiss()
  • send_keys() - Send keys to alert
    • Syntax:
      • alert = Alert(driver)
      • alert.send_keys("Testing Colleges")
  • text - This method gets the alert message.
    • Syntax:
      • alert = Alert(driver)
      • message = alert.text
      • print(message)

Program:
  1. from selenium import webdriver
  2. from selenium.webdriver.common.alert import Alert
  3. from selenium.webdriver.common.by import By

  4. driver = webdriver.Chrome()
  5. driver.get("https://testingcolleges.blogspot.com/2023/08/alerts-demo-pages.html")
  6. # Confirm Alert box
  7. altbox = driver.find_element(By.ID, "confirmbox")
  8. altbox.click()
  9. time.sleep(2)

  10. alert = Alert(driver)
  11. # print the alert message
  12. print(alert.text)
  13. # accept the alert box
  14. time.sleep(2)
  15. # close the window
  16. driver.close()

OUTPUT:
    













No comments:

Post a Comment