Python Code Examples using Selenium Grid

These examples are for selenium version V3. See selenium version 4 python examples.

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@HUB_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 3.14.0 for your selenium grid, install the latest 3.14.x for Python.

pip install selenium==3.14.1
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
Python Selenium Proxy Example

Single Python test


#file test_1.py
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
					 
					 
driver = webdriver.Remote(
   command_executor="https://USERNAME:ACCESS_KEY@HUB_SUBDOMAIN.gridlastic.com/wd/hub",
   desired_capabilities={
            "browserName": "chrome",
            "browserVersion": "latest",
            "video": "True",
            "platform": "WIN10",
            "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
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
import logging
logging.basicConfig(filename="log.txt", level=logging.INFO)

class TestExamples(unittest.TestCase):

    def setUp(self):
        self.driver  = webdriver.Remote(
		command_executor="https://USERNAME:ACCESS_KEY@HUB_SUBDOMAIN.gridlastic.com/wd/hub",
		desired_capabilities={
            "browserName": "chrome",
            "browserVersion": "latest",
            "video": "True",
            "platform": "WIN10",
            "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
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
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
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 HUB_SUBDOMAIN.gridlastic.com --port 80 --variables capabilities.json --capability browserName chrome --capability browserVersion latest --capability platform WIN10 --capability platformName windows test_pytest_selenium.py
RUN - not referencing a json variables file
py.test -n 2 --driver Remote --host USERNAME:ACCESS_KEY@HUB_SUBDOMAIN.gridlastic.com --port 80 --capability video True --capability browserName chrome --capability browserVersion latest --capability platform WIN10 --capability platformName windows test_pytest_selenium.py
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.


Python Selenium Proxy Example

Use a selenium proxy to route your tests via our hosted Squid proxy or use your own proxy locally to test behind firewall internal sites using Gridlastic Connect Proxy Setup.

PROXY = "hub_subdomain.gridlastic.com:8001"; # hosted Squid proxy on your selenium grid hub
#PROXY = "your_gridlastic_connect_subdomain.gridlastic.com:9999"; # An example Gridlastic Connect endpoint

desired_capabilities['proxy'] = {
    "httpProxy":PROXY,
    "ftpProxy":PROXY,
    "sslProxy":PROXY,
    "noProxy":None,
    "proxyType":"MANUAL",
    "class":"org.openqa.selenium.Proxy",
    "autodetect":False
}



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.