Python Code Examples using Selenium Grid

These python code examples will get you a quick start using a selenium grid to run a single test, multiple tests in parallel and also using the Py.test selenium-pytest plugin.

NOTE: To run these examples as is, get a free Gridlastic account and replace USERNAME:ACCESS_KEY@YOUR_SUBDOMAIN and VIDEO_URL parameters with your own credentials found in your Gridlastic dashboard after launching your selenium grid.

To use Python with selenium, first install the latest selenium client version equivalent to your selected selenium grid version. Example: If you selected to use selenium version 2.53.1 for your selenium grid, install the latest 2.53.x for Python.

pip install selenium==2.53.6
NOTE: The python selenium client does not work with selenium version 3.3. Also, starting from selenium version 3.9.1 you must also include "platformName": "windows" in the request when testing with firefox and IE.

EXAMPLES
Single Python test
Multiple Python tests in parallel
Py.test plugin pytest-selenium

Single Python test


#file test_1.py
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
					 
					 
driver = webdriver.Remote(
   command_executor="http://USERNAME:ACCESS_KEY@YOUR_SUBDOMAIN.gridlastic.com:80/wd/hub",
   desired_capabilities={
            "browserName": "chrome",
            "version": "latest",
            "video": "True",
            "platform": "VISTA",
            "platformName": "windows",
        })
print ("Video: " + VIDEO_URL + driver.session_id)
  
try:
    driver.implicitly_wait(30)
    driver.maximize_window() # Note: driver.maximize_window does not work on Linux selenium version v2, instead set window size and window position like driver.set_window_position(0,0) and driver.set_window_size(1920,1080)
    driver.get("http://www.python.org")
    assert "Python" in driver.title
    elem = driver.find_element_by_name("q")
    elem.send_keys("documentation")
    elem.send_keys(Keys.RETURN)
    assert "No results found." not in driver.page_source
finally:
    driver.quit()
RUN
python test_1.py


Multiple Python tests in parallel

Here we use the Python built-in unittest framework (PyUnit) and Py.test with the plugin pytest-xdist and plugin pytest-rerunfailures to run parallel tests and rerun failed tests, logging output to a log.txt file. You could also use nose to run tests in parallel.

INSTALL
pip install pytest
pip install pytest-xdist
pip install pytest-rerunfailures

#file test_unittest.py
import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import logging
logging.basicConfig(filename="log.txt", level=logging.INFO)

class TestExamples(unittest.TestCase):

    def setUp(self):
        self.driver  = webdriver.Remote(
		command_executor="http://USERNAME:ACCESS_KEY@YOUR_SUBDOMAIN.gridlastic.com:80/wd/hub",
		desired_capabilities={
            "browserName": "chrome",
            "version": "latest",
            "video": "True",
            "platform": "VISTA",
            "platformName": "windows",
        })
        self.driver.implicitly_wait(30)
        self.driver.maximize_window() # Note: driver.maximize_window does not work on Linux, instead set window size and window position like driver.set_window_position(0,0) and driver.set_window_size(1920,1080)

    def test_one(self):
        try:
           driver = self.driver
           driver.get("http://www.python.org")
           self.assertIn("Python", driver.title)
           elem = driver.find_element_by_name("q")
           elem.send_keys("documentation")
           elem.send_keys(Keys.RETURN)
           assert "No results found." not in driver.page_source
        finally:
           logging.info("Test One Video: " + VIDEO_URL + driver.session_id)
		   
    def test_two(self):
        try:
           driver = self.driver
           driver.get("http://www.google.com")
           elem = driver.find_element_by_name("q")
           elem.send_keys("webdriver")
           elem.send_keys(Keys.RETURN)
        finally:
           	logging.info("Test Two Video: " + VIDEO_URL + driver.session_id)
			
    def tearDown(self):
        self.driver.quit()

if __name__ == "__main__":
    unittest.main()
RUN
py.test -n 2 --rerun 2 test_unittest.py
LOG OUTPUT EXAMPLE (log.txt):
Test One Video: https://s3-us-west-1.amazonaws.com/027a15f2-530d-31e5-f8cc-7ceaf6355377/239a61a7-c526-ceb8-9sfd-1752b682a464/play.html?4f461455-51b5-42c6-a454-1320b302862d
Test Two Video: https://s3-us-west-1.amazonaws.com/027a15f2-530d-31e5-f8cc-7ceaf6355377/239a61a7-c526-ceb8-9sfd-1752b682a464/play.html?5505d8ed-02da-44eb-b8d4-aa010ef465f7
This runs the 2 tests in parallel. Py.test looks for tests using a naming like test_* and you can specify how many tests you want to run in parallel like py.test -n NUM. The Gridlastic auto scaling functionality then launches grid nodes to meet demand.


Py.test plugin pytest-selenium

The pytest-selenium plugin works very well with selenium tests and in the below example we will run 2 tests in parallel and log the output to log.txt file. We will also use Py.test variables and store the selenium grid credentials in a json file to pass in on the command line.

INSTALL
pip install pytest-selenium
pip install pytest-variables
JSON config file (capabilities.json)
{ "capabilities": {
	"video": "True",
	"gridlasticUser": USERNAME,
	"gridlasticKey": ACCESS_KEY
	}
}

#file test_pytest_selenium.py
import pytest
from selenium.webdriver.common.keys import Keys
import logging
logging.basicConfig(filename="log.txt", level=logging.INFO)

@pytest.fixture
def selenium(selenium):
    selenium.implicitly_wait(30)
    selenium.maximize_window()
    return selenium
	
def test_one(selenium):
	try:
		selenium.get("http://www.python.org")
		assert "Python" in selenium.title
		elem = selenium.find_element_by_name("q")
		elem.send_keys("documentation")
		elem.send_keys(Keys.RETURN)
		assert "No results found." not in selenium.page_source
	finally:
		logging.info("Test One Video: " + VIDEO_URL + selenium.session_id)

def test_two(selenium):
	try:
		selenium.get("http://www.google.com")
		elem = selenium.find_element_by_name("q")
		elem.send_keys("webdriver")
		elem.send_keys(Keys.RETURN)
	finally:
		logging.info("Test Two Video: " + VIDEO_URL + selenium.session_id)
RUN - referencing a json variables file
py.test -n 2 --driver Remote --host YOUR_SUBDOMAIN.gridlastic.com --port 80 --variables capabilities.json --capability browserName chrome --capability version latest --capability platform VISTA --capability platformName windows test_pytest_selenium.py
RUN - not referencing a json variables file
py.test -n 2 --driver Remote --host USERNAME:ACCESS_KEY@YOUR_SUBDOMAIN.gridlastic.com --port 80 --capability video True --capability browserName chrome --capability version latest --capability platform VISTA --capability platformName windows test_pytest_selenium.py
LOG OUTPUT EXAMPLE (log.txt):
Test One Video: https://s3-us-west-1.amazonaws.com/027a15f2-530d-31e5-f8cc-7ceaf6355377/239a61a7-c526-ceb8-9sfd-1752b682a464/play.html?4f461455-51b5-42c6-a454-1320b302862d
Test Two Video: https://s3-us-west-1.amazonaws.com/027a15f2-530d-31e5-f8cc-7ceaf6355377/239a61a7-c526-ceb8-9sfd-1752b682a464/play.html?5505d8ed-02da-44eb-b8d4-aa010ef465f7
This runs the 2 tests in parallel. Py.test looks for tests using a naming like test_* and you can specify how many tests you want to run in parallel like py.test -n NUM. The Gridlastic auto scaling functionality then launches grid nodes to meet demand.



NOTE: Gridlastic auto scaling requires all 3 test environment parameters platform, browser and browser version to be specified in each request in order to launch test nodes to fulfill test demand. Video recording is optional. See test environments for capabilities options.
It is important to ensure that "driver.quit()" is always called for proper test execution and creation of video recordings of failed tests.