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
# Initialize the WebDriver (example with Chrome)
driver = webdriver.Chrome()
try:
# Open the target web page
driver.get('https://example.com')
# Wait until the element with id 'username-input' is present
wait = WebDriverWait(driver, 10)
element = wait.until(EC.presence_of_element_located((By.ID, 'username-input')))
# Use JavaScript to modify the placeholder attribute
driver.execute_script("arguments[0].setAttribute('placeholder', 'Enter your username')", element)
# Verify the placeholder attribute is updated
updated_placeholder = element.get_attribute('placeholder')
assert updated_placeholder == 'Enter your username', f"Expected placeholder to be 'Enter your username' but got '{updated_placeholder}'"
finally:
driver.quit()This script starts by opening the browser and navigating to the target page.
It waits explicitly for the element with id 'username-input' to be present to avoid errors.
Then it uses Selenium's execute_script method to run JavaScript that changes the element's placeholder attribute.
Finally, it retrieves the updated attribute and asserts it matches the expected value.
The finally block ensures the browser closes even if the test fails.