Thursday, April 30, 2015

Input text using 'Send_Keys' in Selenium

Selenium supports various methods to enter text in 'Input' Text field. One of which is using 'send_keys'.

'send_keys' simulates keyboard inputs, you can enter text as you are typing in keyboard. You can also input special keys like RETURN, F1, F2, ALT etc.. Special keys can be send using Keys class imported from selenium.webdriver.common.keys:

Let us write small test code to Automate the following steps
  1. Open 'Google' web page
  2. Asset if Page got loaded by looking at the title
  3. Input some text in the Search Bar using 'send_keys'
  4. Input 'RETURN' key to search
  5. Assert if the Search results are loaded by looking at the Page title

Code:
#!/bin/python
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
 
#create instance for Firefox driver
driver = webdriver.Firefox()

#Open Google.com website
driver.get("http://www.google.com")

#assertion
assert "Google" in driver.title

#Enter text in the input field
search_input = driver.find_element_by_id("lst-ib")
search_input.send_keys("Selenium")
search_input.send_keys(Keys.RETURN)

#assertion
assert "Selenium" in driver.title

#close the browser
driver.quit()

Explanation:
I hope most of the code is self explanatory except find_by_element_id which is used to locate the
 element by unique ID.

Let us see how to use Browser developer tools to inspect an Element. If you press F12 in Chrome/Firefox, it will open 'Developer Tools', which has many features. But, let us limit our self to find an element properties.

From the 'Developer Tool' which usually opens in the bottom of the page, click on 'Inspect Element' button and place it on the element (in our case Input field) to get the properties. Look at the following screenshot.


Here is the HTML code for the element
<input id="lst-ib" class="gsfi" type="text ...></input>
 
Webdriver provides various ways to find an element, "find_element_by_id" is one of them, which is used to find an element by using it's ID. In the above example the element id is "lst-ib". So, we have used driver.find_element_by_id("lst-ib") to get the element . 

After locating an element, we can perform various operations on it like Input some text, Click() etc..

No comments:

Post a Comment