0
0
Selenium Pythontesting~5 mins

Prompt alert with text input in Selenium Python

Choose your learning style9 modes available
Introduction

Prompt alerts let websites ask you to type something. Testing them ensures your site handles user input correctly.

When a website asks for your name or other info in a popup.
When testing forms that use prompt alerts for extra input.
When verifying that the input text is accepted and processed.
When checking how your app reacts to canceling or submitting prompt alerts.
Syntax
Selenium Python
alert = driver.switch_to.alert
alert.send_keys('your text')
alert.accept()

Use switch_to.alert to access the prompt alert.

send_keys() types text into the prompt.

Examples
Types 'Hello' into the prompt and clicks OK.
Selenium Python
alert = driver.switch_to.alert
alert.send_keys('Hello')
alert.accept()
Types '12345' but clicks Cancel instead of OK.
Selenium Python
alert = driver.switch_to.alert
alert.send_keys('12345')
alert.dismiss()
Sample Program

This script opens a page with a button that triggers a prompt alert. It types 'Alice' into the prompt and accepts it. Then it prints the page text which should greet Alice.

Selenium Python
from selenium import webdriver
from selenium.webdriver.common.by import By
import time

# Setup driver
options = webdriver.ChromeOptions()
options.add_argument('--headless=new')
driver = webdriver.Chrome(options=options)

try:
    # Open a simple page with prompt alert
    driver.get('data:text/html,<script>function showPrompt() { var result = prompt(\'Enter your name:\'); document.body.innerHTML = result ? `Hello, ${result}!` : 'No name entered.'; }</script><button onclick="showPrompt()">Click me</button>')

    # Click the button to open prompt
    button = driver.find_element(By.TAG_NAME, 'button')
    button.click()

    # Switch to prompt alert
    alert = driver.switch_to.alert

    # Send text input
    alert.send_keys('Alice')

    # Accept the prompt
    alert.accept()

    time.sleep(1)  # Wait for page update

    # Verify the page shows the input
    body_text = driver.find_element(By.TAG_NAME, 'body').text
    print(body_text)

finally:
    driver.quit()
OutputSuccess
Important Notes

Always switch to the alert before interacting with it.

Use accept() to click OK and dismiss() to click Cancel.

Prompt alerts pause script execution until handled.

Summary

Prompt alerts ask users for text input in a popup.

Use switch_to.alert to access and send_keys() to type text.

Accept or dismiss the alert to continue the test.