sendKeys Selenium Examples

Here are some examples of using the sendKeys method in Selenium to interact with web applications:

Example #1: Entering text in a text field

from selenium import webdriver

# Assuming you have a web driver instance, such as ChromeDriver
driver = webdriver.Chrome()

# Navigate to a web page with a text field
driver.get("https://github.codetryout.com/")

# Locate the text field element
text_field = driver.find_element_by_id("CodeTryout")

# Enter text into the text field
text_field.send_keys("Hello, world!")

# Close the browser
driver.quit()

Example 2: Typing special characters

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

# Assuming you have a web driver instance, such as ChromeDriver
driver = webdriver.Chrome()

# Navigate to a web page with a text field
driver.get("https://example.com")

# Locate the text field element
text_field = driver.find_element_by_id("myTextField")

# Enter text with special characters
text_field.send_keys(Keys.SHIFT + "open" + Keys.SPACE + "sesame" + Keys.ENTER)

# Close the browser
driver.quit()

Example 3: Simulating keyboard events

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

# Assuming you have a web driver instance, such as ChromeDriver
driver = webdriver.Chrome()

# Navigate to a web page with a text field
driver.get("https://example.com")

# Locate the text field element
text_field = driver.find_element_by_id("myTextField")

# Enter text and simulate keyboard events
text_field.send_keys("Hello")
text_field.send_keys(Keys.ARROW_DOWN)
text_field.send_keys(Keys.ENTER)

# Close the browser
driver.quit()

These examples demonstrate how to use the sendKeys method to interact with text fields in web applications. You can modify them based on your specific use case and the elements you’re targeting on your web page. Remember to adjust the element locator strategy (e.g., find_element_by_id, find_element_by_name, find_element_by_xpath, etc.) according to your HTML structure.