Selenium webdriver can enter keypresses or type on any webpage. Selenium is the Python module to automate web browsers. The web driver is connected to both the web browser and the Python code.

The selenium webdriver starts the browser, the browser loads the webpage, selects the textbox and types.

Related course:

keyboard

selenium keyboard

To use keypress in selenium, first you need to import some stuff from the selenium module:

1
2
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys

In the example below, a web browser is started. Then it searches for an HTML element by its id (elements often have a unique id). We grab the html element by its unique identifier like this:

1
input=browser.find_element_by_id("searchInput")

Then the method .send_keys() is used to type into the element. Don’t forget to also send the enter or return key if necessary.

1
2
input.send_keys("Python")
input.send_keys(Keys.ENTER)

The selenium keyboard code example below does all that. In this example it does an automated searh on wikipedia, but the principle works on any site.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
import time

browser=webdriver.Firefox()
try:
browser.get("https://en.wikipedia.org")
print(browser.title)
input=browser.find_element_by_id("searchInput")
input.send_keys("Python")
input.send_keys(Keys.ENTER)
wait=WebDriverWait(browser,10)
wait.until(EC.presence_of_element_located((By.ID,"content")))
print(browser.title)
#print(browser.get_cookies())
#print(browser.page_source)
time.sleep(10)
finally:
browser.close()

selenium keyboard

If you are new to selenium, then I highly recommend this book.

Download examples