2.Getting Started

2.1.Simple Usage

If you have installed Selenium Python bindings, you can start using it fromPython like this.

fromseleniumimportwebdriverfromselenium.webdriver.common.keysimportKeysfromselenium.webdriver.common.byimportBydriver=webdriver.Firefox()driver.get("http://www.python.org")assert"Python"indriver.titleelem=driver.find_element(By.NAME,"q")elem.clear()elem.send_keys("pycon")elem.send_keys(Keys.RETURN)assert"No results found."notindriver.page_sourcedriver.close()

The above script can be saved into a file (eg:-python_org_search.py), then itcan be run like this:

pythonpython_org_search.py

Thepython which you are running should have theselenium module installed.

2.2.Example Explained

Theselenium.webdriver module provides all the WebDriver implementations.Currently supported WebDriver implementations are Firefox, Chrome, IE andRemote. TheKeys class provide keys in the keyboard like RETURN, F1, ALT etc.TheBy class is used to locate elements within a document.

fromseleniumimportwebdriverfromselenium.webdriver.common.keysimportKeysfromselenium.webdriver.common.byimportBy

Next, the instance of Firefox WebDriver is created.

driver=webdriver.Firefox()

Thedriver.get method will navigate to a page given by the URL. WebDriverwill wait until the page has fully loaded (that is, the “onload” event hasfired) before returning control to your test or script.Be aware that if yourpage uses a lot of AJAX on load then WebDriver may not know when it hascompletely loaded:

driver.get("http://www.python.org")

The next line is an assertion to confirm that title has the word “Python” in it:

assert"Python"indriver.title

WebDriver offers a number of ways to find elements using thefind_element method. For example, the input text element can be locatedby itsname attribute using thefind_element method and using By.NAME as its first parameter.A detailed explanation of finding elements is available in theLocating Elementschapter:

elem=driver.find_element(By.NAME,"q")

Next, we are sending keys, this is similar to entering keys using your keyboard.Special keys can be sent using theKeys class imported fromselenium.webdriver.common.keys. To be safe, we’ll first clear anypre-populated text in the input field (e.g. “Search”) so it doesn’t affect oursearch results:

elem.clear()elem.send_keys("pycon")elem.send_keys(Keys.RETURN)

After submission of the page, you should get the result if there is any. Toensure that some results are found, make an assertion:

assert"No results found."notindriver.page_source

Finally, the browser window is closed. You can also call thequit method insteadofclose. Thequit method will exit the browser whereasclose will close onetab, but if just one tab was open, by default most browsers will exit entirely.:

driver.close()

2.3.Using Selenium to write tests

Selenium is mostly used for writing test cases. Theselenium package itselfdoesn’t provide a testing tool/framework. You can write test cases usingPython’s unittest module. Alternatively, you may considerpytest for writing tests.

In this chapter, we useunittest as the framework of choice. Here is themodified example which uses the unittest module. This is a test for thepython.orgsearch functionality:

importunittestfromseleniumimportwebdriverfromselenium.webdriver.common.keysimportKeysfromselenium.webdriver.common.byimportByclassPythonOrgSearch(unittest.TestCase):defsetUp(self):self.driver=webdriver.Firefox()deftest_search_in_python_org(self):driver=self.driverdriver.get("http://www.python.org")self.assertIn("Python",driver.title)elem=driver.find_element(By.NAME,"q")elem.send_keys("pycon")elem.send_keys(Keys.RETURN)self.assertNotIn("No results found.",driver.page_source)deftearDown(self):self.driver.close()if__name__=="__main__":unittest.main()

You can run the above test case from a shell like this:

pythontest_python_org_search.py.----------------------------------------------------------------------Ran1testin15.566sOK

The above result shows that the test has been successfully completed.

Note: To run the above test in IPython or Jupyter, you should pass a couple ofarguments to themain function as shown below:

unittest.main(argv=['first-arg-is-ignored'],exit=False)

2.4.Walkthrough of the example

Initially, all the basic modules required are imported. Theunittest module is a built-in Pythonmodule based on Java’s JUnit. This module provides the framework for organizing thetest cases. Theselenium.webdriver module provides all the WebDriverimplementations. Currently supported WebDriver implementations are: Firefox,Chrome, IE and Remote. TheKeys class provides keys in the keyboard likeRETURN, F1, ALT etc. TheBy class is used to locate elements within a document.

importunittestfromseleniumimportwebdriverfromselenium.webdriver.common.keysimportKeysfromselenium.webdriver.common.byimportBy

The test case class is inherited fromunittest.TestCase. Inheriting fromtheTestCase class is the way to tellunittest module that this is a test case:

classPythonOrgSearch(unittest.TestCase):

ThesetUp method is part of initialization. This method will get called before everytest function which you are going to write in this test case class. Here youare creating an instance of a Firefox WebDriver.

defsetUp(self):self.driver=webdriver.Firefox()

This is the test case method. The test case method should always start withcharacterstest. The first line inside this method creates a local referenceto the driver object created insetUp method.

deftest_search_in_python_org(self):driver=self.driver

Thedriver.get method will navigate to a page given by the URL. WebDriverwill wait until the page has fully loaded (that is, the “onload” event hasfired) before returning control to your test or script.Be aware that if yourpage uses a lot of AJAX on load then WebDriver may not know when it hascompletely loaded:

driver.get("http://www.python.org")

The next line is an assertion to confirm that title has the word “Python” in it:

self.assertIn("Python",driver.title)

WebDriver offers a number of ways to find elements using thefind_element method. For example, the input text element can be locatedby itsname attribute using thefind_element method. Detailedexplanation of finding elements is available in theLocating Elementschapter:

elem=driver.find_element(By.NAME,"q")

Next, we are sending keys, this is similar to entering keys using your keyboard.Special keys can be sent using theKeys class imported fromselenium.webdriver.common.keys:

elem.send_keys("pycon")elem.send_keys(Keys.RETURN)

After submission of the page, you should get the result as per search if thereis any. To ensure that some results are found, make an assertion:

self.assertNotIn("No results found.",driver.page_source)

ThetearDown method will get called after every test method. This is a placeto do all cleanup actions. In the current method, the browser window is closed.You can also call thequit method instead ofclose. Thequit method will exit theentire browser, whereasclose will close a tab, but if it is the only tabopened, by default most browsers will exit entirely.:

deftearDown(self):self.driver.close()

Final lines are some boiler plate code to run the test suite:

if__name__=="__main__":unittest.main()

2.5.Using Selenium with remote WebDriver

To use the remote WebDriver, you should have the Selenium server running. To runthe server, use this command:

java-jarselenium-server-standalone-2.x.x.jar

While running the Selenium server, you could see a message looking like this:

15:43:07.541INFO-RemoteWebDriverinstancesshouldconnectto:http://127.0.0.1:4444/wd/hub

The above line says that you can use this URL for connecting to the remoteWebDriver. Here are some examples:

fromseleniumimportwebdriverdriver=webdriver.Remote(command_executor='http://127.0.0.1:4444/wd/hub',options=webdriver.ChromeOptions())driver=webdriver.Remote(command_executor='http://127.0.0.1:4444/wd/hub',options=webdriver.FirefoxOptions())