Selenium Python bindings provides a simple API to write
functional/acceptance tests using Selenium WebDriver. Through
Selenium Python API you can access all functionalities of Selenium
WebDriver in an intuitive way.

You can download Python bindings for Selenium from the PyPI page for
selenium package. However,
a better approach would be to use
pip to
install the selenium package. Python 3.4 has pip available in the
standard library.
Using pip, you can install selenium like this:

pip install selenium

You may consider using virtualenv
to create isolated Python environments. Python 3.4 has pyvenv
which is almost same as virtualenv.

The Selenium server is only required, if you want to use the remote
WebDriver. See the Using Selenium with remote WebDriver section for
more details. If you are a beginner learning Selenium, you can
skip this section and proceed with next chapter.

Selenium server is a Java program. Java Runtime Environment (JRE) 1.6
or newer version is recommended to run Selenium server.

You can download Selenium server 2.x from the download page of
selenium website. The file name
should be something like this:
selenium-server-standalone-2.x.x.jar. You can always download the
latest 2.x version of Selenium server.

If Java Runtime Environment (JRE) is not installed in your system, you
can download the JRE from the Oracle website.
If you are using a GNU/Linux system and have root access in your system,
you can also use your operating system instructions to install JRE.

If java command is available in the PATH (environment variable),
you can start the Selenium server using this command:

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

Replace 2.x.x with actual version of Selenium server you downloaded
from the site.

If JRE is installed as a non-root user and/or if it is
not available in the PATH (environment variable), you can type the
relative or absolute path to the java command. Similarly, you can
provide relative or absolute path to Selenium server jar file.
Then, the command will look something like this:

The selenium.webdriver module provides all the WebDriver
implementations. Currently supported WebDriver implementations are
Firefox, Chrome, Ie and Remote. The Keys class provide keys in the
keyboard like RETURN, F1, ALT etc.

The driver.get method will navigate to a page given by the URL.
WebDriver will wait until the page has fully loaded (that is, the
“onload” event has fired) before returning control to your test or
script. It’s worth noting that if your page uses a lot of AJAX on
load then WebDriver may not know when it has completely loaded.:

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

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

assert"Python"indriver.title

WebDriver offers a number of ways to find elements using one of the
find_element_by_* methods. For example, the input text element can
be located by its name attribute using find_element_by_name
method. Detailed explanation of finding elements is available in the
Locating Elements chapter:

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 send using Keys class imported from
selenium.webdriver.common.keys:

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

After submission of the page, you should get the result if there is any.
To ensure 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 quit
method instead of close. The quit will exit entire browser whereas
close` will close one tab, but if just one tab was open, by default most
browser will exit entirely.:

Selenium is mostly used for writing test cases. The selenium
package itself doesn’t provide a testing tool/framework. You can
write test cases using Python’s unittest module. The other options for
a tool/framework are py.test and nose.

In this chapter, we use unittest as the framework of choice. Here
is the modified example which uses unittest module. This is a test
for python.org search functionality:

Initially, all the basic modules required are imported. The unittest module is a built-in
Python based on Java’s JUnit. This module provides the framework for
organizing the test cases. The selenium.webdriver module provides
all the WebDriver implementations. Currently supported WebDriver
implementations are Firefox, Chrome, Ie and Remote. The Keys class
provide keys in the keyboard like RETURN, F1, ALT etc.

The test case class is inherited from unittest.TestCase.
Inheriting from TestCase class is the way to tell unittest module
that this is a test case:

class PythonOrgSearch(unittest.TestCase):

The setUp is part of initialization, this method will get called
before every test function which you are going to write in this test
case class. Here you are creating the instance of Firefox WebDriver.

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

This is the test case method. The test case method should always start
with characters test. The first line inside this method create a
local reference to the driver object created in setUp method.

deftest_search_in_python_org(self):driver=self.driver

The driver.get method will navigate to a page given by the URL.
WebDriver will wait until the page has fully loaded (that is, the
“onload” event has fired) before returning control to your test or
script. It’s worth noting that if your page uses a lot of AJAX on
load then WebDriver may not know when it has completely loaded.:

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

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

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

WebDriver offers a number of ways to find elements using one of the
find_element_by_* methods. For example, the input text element can
be located by its name attribute using find_element_by_name
method. Detailed explanation of finding elements is available in the
Locating Elements chapter:

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 send using Keys class imported from
selenium.webdriver.common.keys:

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

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

assert"No results found."notindriver.page_source

The tearDown method will get called after every test method. This
is a place to do all cleanup actions. In the current method, the
browser window is closed. You can also call quit method instead of
close. The quit will exit the entire browser, whereas close
will close a tab, but if it is the only tab opened, by default most
browser will exit entirely.:

The first thing you’ll want to do with WebDriver is navigate to a
link. The normal way to do this is by calling get method:

driver.get("http://www.google.com")

WebDriver will wait until the page has fully loaded (that is, the
onload event has fired) before returning control to your test or
script. It’s worth noting that if your page uses a lot of AJAX on
load then WebDriver may not know when it has completely loaded. If
you need to ensure such pages are fully loaded then you can use
waits.

Just being able to go to places isn’t terribly useful. What we’d
really like to do is to interact with the pages, or, more
specifically, the HTML elements within a page. First of all, we need
to find one. WebDriver offers a number of ways to find elements. For
example, given an element defined as:

You can also look for a link by its text, but be careful! The text
must be an exact match! You should also be careful when using XPATH
in WebDriver. If there’s more than one element that matches the
query, then only the first will be returned. If nothing can be found,
a NoSuchElementException will be raised.

WebDriver has an “Object-based” API; we represent all types of
elements using the same interface. This means that although you may
see a lot of possible methods you could invoke when you hit your IDE’s
auto-complete key combination, not all of them will make sense or be
valid. Don’t worry! WebDriver will attempt to do the Right Thing, and
if you call a method that makes no sense (“setSelected()” on a “meta”
tag, for example) an exception will be raised.

So, you’ve got an element. What can you do with it? First of all, you
may want to enter some text into a text field:

element.send_keys("some text")

You can simulate pressing the arrow keys by using the “Keys” class:

element.send_keys(" and some",Keys.ARROW_DOWN)

It is possible to call send_keys on any element, which makes it
possible to test keyboard shortcuts such as those used on GMail. A
side-effect of this is that typing something into a text field won’t
automatically clear it. Instead, what you type will be appended to
what’s already there. You can easily clear the contents of a text
field or textarea with clear method:

We’ve already seen how to enter text into a textarea or text field,
but what about the other elements? You can “toggle” the state of
drop down, and you can use “setSelected” to set something like an
OPTION tag selected. Dealing with SELECT tags isn’t too bad:

Once you’ve finished filling out the form, you probably want to submit
it. One way to do this would be to find the “submit” button and click
it:

# Assume the button has the ID "submit" :)driver.find_element_by_id("submit").click()

Alternatively, WebDriver has the convenience method “submit” on every
element. If you call this on an element within a form, WebDriver will
walk up the DOM until it finds the enclosing form and then calls
submit on that. If the element isn’t in a form, then the
NoSuchElementException will be raised:

Selenium WebDriver has built-in support for handling popup dialog
boxes. After you’ve triggerd and action that would open a popup, you
can access the alert with the following:

alert=driver.switch_to_alert()

This will return the currently open alert object. With this object
you can now accept, dismiss, read its contents or even type into a
prompt. This interface works equally well on alerts, confirms,
prompts. Refer to the API documentation for more information.

Earlier, we covered navigating to a page using the “get” command (
driver.get("http://www.example.com")) As you’ve seen, WebDriver
has a number of smaller, task-focused interfaces, and navigation is a
useful task. To navigate to a page, you can use get method:

driver.get("http://www.example.com")

To move backwards and forwards in your browser’s history:

driver.forward()driver.back()

Please be aware that this functionality depends entirely on the
underlying driver. It’s just possible that something unexpected may
happen when you call these methods if you’re used to the behaviour of
one browser over another.

Before we leave these next steps, you may be interested in
understanding how to use cookies. First of all, you need to be on the
domain that the cookie will be valid for:

# Go to the correct domain
driver.get("http://www.example.com")
# Now set the cookie. This one's valid for the entire domain
cookie = {‘name’ : ‘foo’, ‘value’ : ‘bar’}
driver.add_cookie(cookie)
# And now output all the available cookies for the current URL
driver.get_cookies()

Use this when you know id attribute of an element. With this
strategy, the first element with the id attribute value matching the
location will be returned. If no element has a matching id
attribute, a NoSuchElementException will be raised.

Use this when you know name attribute of an element. With this
strategy, the first element with the name attribute value matching
the location will be returned. If no element has a matching name
attribute, a NoSuchElementException will be raised.

XPath is the language used for locating nodes in an XML document. As
HTML can be an implementation of XML (XHTML), Selenium users can
leverage this powerful language to target elements in their web
applications. XPath extends beyond (as well as supporting) the simple
methods of locating by id or name attributes, and opens up all sorts
of new possibilities such as locating the third checkbox on the page.

One of the main reasons for using XPath is when you don’t have a
suitable id or name attribute for the element you wish to locate. You
can use XPath to either locate the element in absolute terms (not
advised), or relative to an element that does have an id or name
attribute. XPath locators can also be used to specify elements via
attributes other than id and name.

Absolute XPaths contain the location of all elements from the root
(html) and as a result are likely to fail with only the slightest
adjustment to the application. By finding a nearby element with an id
or name attribute (ideally a parent element) you can locate your
target element based on the relationship. This is much less likely to
change and can make your tests more robust.

Use this when you know link text used within an anchor tag. With this
strategy, the first element with the link text value matching the
location will be returned. If no element has a matching link text
attribute, a NoSuchElementException will be raised.

Use this when you want to locate an element by tag name. With this
strategy, the first element with the given tag name will be returned.
If no element has a matching tag name, a NoSuchElementException
will be raised.

Use this when you want to locate an element by class attribute name.
With this strategy, the first element with the matching class attribute
name will be returned. If no element has a matching class attribute name,
a NoSuchElementException will be raised.

Use this when you want to locate an element by CSS selector syntaxt.
With this strategy, the first element with the matching CSS selector
will be returned. If no element has a matching CSS selector,
a NoSuchElementException will be raised.

These days most of the web apps are using AJAX techniques. When a
page is loaded to browser, the elements within that page may load at
different time intervals. This makes locating elements difficult, if
the element is not present in the DOM, it will raise
ElementNotVisibleException exception. Using waits, we can solve
this issue. Waiting provides some time interval between actions
performed - mostly locating element or any other operation with the
element.

Selenium Webdriver provides two types of waits - implicit & explicit.
An explicit wait makes WebDriver to wait for a certain condition to
occur before proceeding further with executions. An implicit wait
makes WebDriver to poll the DOM for a certain amount of time when
trying to locate an element.

An explicit waits is code you define to wait for a certain condition
to occur before proceeding further in the code. The worst case of
this is time.sleep(), which sets the condition to an exact time period
to wait. There are some convenience methods provided that help you
write code that will wait only as long as required. WebDriverWait in
combination with ExpectedCondition is one way this can be
accomplished.

This waits up to 10 seconds before throwing a TimeoutException or if
it finds the element will return it in 0 - 10 seconds. WebDriverWait
by default calls the ExpectedCondition every 500 milliseconds until it
returns successfully. A successful return is for ExpectedCondition
type is Boolean return true or not null return value for all other
ExpectedCondition types.

Expected Conditions

There are some common conditions that are frequently come across when
automating web browsers. Listed below are Implementations of
each. Selenium Python binding provides some convienence methods so you
don’t have to code an expected_condition class yourself or create your
own utility package for them.

An implicit wait is to tell WebDriver to poll the DOM for a certain
amount of time when trying to find an element or elements if they are
not immediately available. The default setting is 0. Once set, the
implicit wait is set for the life of the WebDriver object instance.

This chapter is a tutorial introduction to page objects design
pattern. A page object represents an area in the web application user
interface that your test is interating. Page objects reduces the
amount of duplicated code and if the user interface changes, the fix
need only changes in one place.

fromelementimportBasePageElementfromlocatorsimportMainPageLocatorsclassSearchTextElement(BasePageElement):locator='q'classBasePage(object):def__init__(self,driver):self.driver=driverclassMainPage(BasePage):search_text_element=SearchTextElement()defis_title_matches(self):return"Python"inself.driver.titledefclick_go_button(self):element=self.driver.find_element(*MainPageLocators.GO_BUTTON)element.click()classSearchResultsPage(BasePage):defis_results_found(self):# Probably should search for this text in the specific page# element, but as for now it works finereturn"No results found."notinself.driver.page_source

Thrown when the selector which is used to find an element does not return
a WebElement. Currently this only happens when the selector is an xpath
expression and it is either syntactically invalid (i.e. it is not a
xpath expression) or the expression does not select WebElements
(e.g. “count(//input)”).

You may want to check if the attribute exists in the particular browser you are
testing against. Some browsers may have different property names for the same
property. (IE8’s .innerText vs. Firefox .textContent)

Possible causes of StaleElementReferenceException include, but not limited to:

You are no longer on the same page, or the page may have refreshed since the element

was located.
* The element may have been removed and re-added to the screen, since it was located.
Such as an element being relocated.
This can happen typically with a javascript framework when values are updated and the
node is rebuilt.
* Element may have been inside an iframe or another context which was refreshed.

ActionChains are a way to automate low level interactions such as
mouse movements, mouse button actions, key press, and context menu interactions.
This is useful for doing more complex actions like hover over and drag and drop.

Generate user actions.

When you call methods for actions on the ActionChains object,
the actions are stored in a queue in the ActionChains object.
When you call perform(), the events are fired in the order they
are queued up.

Generally, all interesting operations to do with interacting with a
document will be performed through this interface.

All method calls will do a freshness check to ensure that the element
reference is still valid. This essentially determines whether or not the
element is still attached to the DOM. If this test fails, then an
StaleElementReferenceException is thrown, and all future calls to this
instance will fail.

This method will return the value of the given property if this is set,
otherwise it returns the value of the attribute with the same name if
that exists, or None.

Values which are considered truthy, that is equals “true” or “false”,
are returned as booleans. All other non-None values are returned as
strings. For attributes or properties which does not exist, None is returned.

Args:

name - Name of the attribute/property to retrieve.

Example:

# Check if the "active" CSS class is applied to an element.is_active="active"intarget_element.get_attribute("class")

file_input=driver.find_element_by_name('profilePic')file_input.send_keys("path/to/profilepic.gif")# Generally it's better to wrap the file path in one of the methods# in os.path to return the actual path to support cross OS testing.# file_input.send_keys(os.path.abspath("path/to/profilepic.gif"))

An expectation for checking that an element is present on the DOM
of a page. This does not necessarily mean that the element is visible.
locator - used to find the element
returns the WebElement once it is located

An expectation for checking that an element, known to be present on the
DOM of a page, is visible. Visibility means that the element is not only
displayed but also has a height and width that is greater than 0.
element is the WebElement
returns the (same) WebElement once it is visible

An expectation for checking that an element is present on the DOM of a
page and visible. Visibility means that the element is not only displayed
but also has a height and width that is greater than 0.
locator - used to find the element
returns the WebElement once it is located and visible

The window object
in DOM has a scrollTo method to
scroll to any position of an opened window. The scrollHeight is a common
property for all elements. The document.body.scrollHeight will give
the height of the entire body of the page.

Select the <inputtype="file"> element and call the send_keys() method passing
the file path, either the path relative to the test script, or an absolute path.
Keep in mind the differences in path names between Windows and Unix systems.