Selenium + Python · Lesson 19 of 43

0/43 done

Module 19: Alerts & Popups

19. Handling Native JavaScript Alerts, Confirms & Prompts

15 minlesson

Your task

Implement accept_alert_get_message(driver):

  1. Switch to alert, save its text, call accept(), and return the text.

Write it in the editor, then press Check answer (Ctrl + Enter).

Handling JavaScript Alerts

python
alert = driver.switch_to.alert
print("Alert message:", alert.text)

# Accept (OK):
alert.accept()

# Dismiss (Cancel):
# alert.dismiss()

Key Takeaways & Walkthrough Summary

JavaScript alert dialogs freeze browser execution until confirmed or canceled. In this lesson, you will master driver.switch_to.alert, reading alert text, accepting confirms, and typing into prompt dialogs. Let's handle alerts!

Part of the Selenium + Python course (Selenium with Python). Practice this concept live in the Selenium Online Compiler or explore our free automation practice form.

Common Doubts & Lesson Q&A

What if an alert is not present when calling switch_to.alert?

Selenium raises NoAlertPresentException. Always use WebDriverWait with EC.alert_is_present() first.

Ready? Solve the task in the editor

Use Check answer to mark it complete. Hints are there if you need them.

Python
Skip