from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException, NoAlertPresentException
# Initialize the WebDriver (assumes chromedriver is in PATH)
driver = webdriver.Chrome()
try:
driver.get('http://example.com/comment') # Replace with actual URL
# Locate the comment input field and submit button
comment_input = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.ID, 'comment'))
)
submit_button = driver.find_element(By.ID, 'submit-comment')
# Enter the XSS test script
xss_payload = "<script>alert('XSS')</script>"
comment_input.clear()
comment_input.send_keys(xss_payload)
# Submit the comment
submit_button.click()
# Wait for the comment to appear on the page
comment_display = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.ID, 'comment-display'))
)
# Check for alert popup - should NOT appear
try:
WebDriverWait(driver, 3).until(EC.alert_is_present())
alert = driver.switch_to.alert
alert_text = alert.text
alert.dismiss()
raise AssertionError(f"Unexpected alert appeared with text: {alert_text}")
except TimeoutException:
# No alert appeared, which is expected
pass
# Verify the displayed comment contains the script tags as plain text
displayed_text = comment_display.text
assert xss_payload in displayed_text, "The script tags are not displayed as plain text"
finally:
driver.quit()This script opens the web page with the comment form.
It waits until the comment input and submit button are present, then enters the XSS payload <script>alert('XSS')</script>.
After clicking submit, it waits for the comment to appear on the page.
It then checks if any alert popup appears. If an alert appears, the test fails because the script executed.
If no alert appears, it verifies that the comment text includes the script tags as plain text, meaning the input was safely handled.
Explicit waits ensure the test waits for elements and alerts properly.
Using By.ID locators is a best practice for stable element selection.