Testing with selenium
The Selenium WebDriver Client Library for Python allows us to leverage all of the functionality available in Selenium WebDriver and interact with Selenium Standalone Server to perform automated testing (both remote and distributed) of browser applications. Selenium WebDriver is widely used for test automation as it is open source and supports popular programming languages such as Python, C #, Java, and others. Furthermore, Selenium RC or Selenium IDE, Selenium WebDriver takes a modern and stable approach to automate browser actions during test execution.
Selenium is an open-source tool, and its library is available in several programming languages for running Web UI Automation tests, and Python is one of them.
Selenium is a web testing framework to automate browsers. It consists of a WebDriver for the browser being used (in this case, Chrome was used and, therefore, Chrome WebDriver) and a Python script to automate the loading of web pages and collect test results.
To install selenium:
pip install selenium
Next create a main.py file with the following imports:
from selenium import webdriverfrom selenium.webdriver.common.keys import Keysfrom selenium.webdriver.common.by import Byfrom time import sleep
These are some basic imports needed to be able to use selenium for testing.
Since I use chrome in this example, you will need to download the chromedriver, located at: https://chromedriver.chromium.org/.
Next we create the ChromeOptions to configure how to start the chrome browser:
options = webdriver.ChromeOptions()options.add_experimental_option('excludeSwitches', ['enable-logging'])options.add_argument("--start-maximized")driver = webdriver.Chrome(executable_path='./chromedriver', options=options)
So with these options we start the Chrome browser in full screen mode.
This can be handy, in case the site is a response site, and will cause some data not to be visible.
Now we can use the driver to actually visit a website:
driver.get('https://www.yahoo.com')
Since some pages can take a bit to fully load, it is wise to add some sleep statements before checking the results.
sleep(4)
Let's execute a search with some keywords:
driver.find_element_by_id("ybar-sbq").send_keys("Selenium testing")driver.find_element_by_id("ybar-search").click()
First we need to find the id of the text box to enter our search keywords. By inspecting the page it's easy to see that the text box is identified by an id with the name: ybar-sbq
For the search button we also need to find the id, in this case: ybar-search
send_keys command will send the search keywords to the element found.
The Click() will execute the search button in this case.