Selenium for Python. Chapter 3. Navigation

  • Tutorial
Continued translation of Selenium informal documentation for Python.
Translated with permission from Baiju Muthukadan.
The original can be found here .


1. Installation
2. First Steps
3. Navigation
4. Finding Elements
5. Expectations
6. Page Objects
7. WebDriver API
8. Application: Frequently Asked Questions

3. Navigation

Presumably, the first thing you want to do with WebDriver is to follow the link. Usually, get method is used for such purposes:


The driver.get method redirects to the page URL provided in the parameter. WebDriver will wait until the page has fully loaded (that is, the onload event is ignored) before passing control to your test or script. It is worth noting that if a page uses a lot of AJAX code at loading, then WebDriver may not recognize if it loaded completely. If you want to guarantee full page loading, you can use the wait (English waits).

3.1. Page Interaction

The ability to click a link is not so useful in itself. What I really want to do is interact with the page, or, to be precise, with the HTML elements on the page. First of all, you need to find them. WebDriver provides a number of ways to search for items. For example, the page has an element defined in this way:

It can be found using any of the following methods:

element = driver.find_element_by_id("passwd-id")
element = driver.find_element_by_name("passwd")
element = driver.find_element_by_xpath("//input[@id='passwd-id']")

You can also search for the address of the hyperlink in the text of the hyperlink, but be careful: the text must match exactly. Also be careful when using XPATH in WebDriver. If there is more than one element satisfying the query conditions, only the first one will be returned. If nothing is found, a NoSuchElementException will be thrown.

WebDriver has an “Object-Oriented” API [Application Programming Interface) - a set of ready-made methods and properties provided by an application (library, service) for use in external software products. The API allows you to use the functionality of the original application (library, service), without delving into the intricacies of the implementation of this functionality. - Note trans.]; we represent all types of elements using the same interface. This means that even though you see a lot of available methods that you can select when pressing the autofill key combination in your IDE [Integrated Development Environment (Eng. Integrated Development Environment) is a software system used by programmers to develop software. - Note per.] not all of them will make sense to you or not all will be valid. Do not worry! WebDriver will try to fix everything, so if you call the method using it incorrectly (for example, use “setSelected ()” for the “meta” tag [meta tags] - HTML tags designed to provide structured metadata about Web page. As a rule, they are indicated in the title of an HTML document. - Note per.]), WebDriver will throw an exception.

So we got the item. What can you do with it? First of all, you want to enter some text in the text box:

element.send_keys("some text")

You can also simulate the keystrokes of the keyboard using the “Keys” class:

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

The send_keys method can be called for any element that allows you to check keyboard shortcuts, such as those used in GMail. There is a side effect that entering a text field does not automatically clear it. Instead, what you type on the keyboard will be added to the one already entered in the field. Clear the contents of the text field or textarea text area easily - using the clear method:


3.2. Filling out forms

We have already considered entering text into a text area or text field, but what about other elements? You can try expanding the drop-down list, after which you can use “setSelected” to highlight tags like OPTION. Working with SELECT tags is not that difficult:

element = driver.find_element_by_xpath("//select[@name='name']")
all_options = element.find_elements_by_tag_name("option")
for option in all_options:
    print("Value is: %s" % option.get_attribute("value"))

Such code will find the first “SELECT” element on the page, and in a loop it will go through all the OPTION tags in turn, reporting their values ​​and highlighting them in turn.

As you can see, this is not the fastest way to work with SELECT elements. The classes supported by the web driver contain one called “Select”, it provides more convenient ways of interaction:

from import Select
select = Select(driver.find_element_by_name('name'))

WebDriver also provides the ability to deselect all items in the drop-down list:

select = Select(driver.find_element_by_id('id'))

This code deselects all OPTION tags of the first SELECT tag on the page.

Let's say for the test you need a list of all the options selected by default. The Select class provides this property (returns a list):

select = Select(driver.find_element_by_xpath("xpath"))
all_selected_options = select.all_selected_options

To get all available options, use:

options = select.options

After the completion of the form is completed, you probably want to “save” the changes [submit - send, send, confirm - Note trans.]. One way to do this is to find the submit button and click on it:

# Предположим, ID кнопки равен "submit" :)

As an alternative to the first method, you can use the submit method, which is available for each element. If you call it on an element inside the form, WebDriver will go through the entire DOM structure until it finds a closing form tag, and then calls submit for it. If the item is not in shape, then a NoSuchElementException is raised:


3.3. Drag and drop

There are two options for “dragging” elements: moving an element by a certain amount, or dragging it to another element:

element = driver.find_element_by_name("source")
target = driver.find_element_by_name("target")
from selenium.webdriver import ActionChains
action_chains = ActionChains(driver)
action_chains.drag_and_drop(element, target)

3.4. Switch between windows and frames

Modern web applications rarely do without frames, and rarely when they are limited to a single window. WebDriver supports switching between named windows using the switch_to_window method:


All calls starting with driver will now be interpreted as being addressed to the received window. But how do you know the name of the window? Take a look at the javascript code or link that opens the window:

Нажмите сюда, чтобы открыть новое окно

You can also send a “window handle” to the “switch_to_window ()” method. Using this feature, you can use the loop to iterate over all open windows, for example, like this:

for handle in driver.window_handles:

You can also switch between frames (frame or iframes):


You can access slave frames by supplying a path separated by a period, or you can get a frame by index:


The following code redirects to a frame named “child”, which in turn belongs to the first sub-frame of the frame “frameName”. The paths to the frames are described completely - from the top level :


When the work with frames is completed, you need to switch back to the main frame, which can be done as follows:


3.5. Popup windows

Selenium WebDriver from the packaging supports the management of pop-up dialogs. After you initiate the launch, a window opens, you can manage it like this:

alert = driver.switch_to_alert()

The code will return the object of the current open window. With this object, you can accept, reject a window question, read its contents, or even enter text at the window’s prompt. The pop-up interaction interface works equally well for both alerts and confirmation requests and prompts. See the API documentation for more information.

3.6. Navigation: history and location

Earlier, we mentioned navigating a link using the “get” command (driver.get (" ")). As you may have noticed, WebDriver for specific cases provides highly specialized, specialized interaction interfaces, and navigation is no exception. To follow the link, you can use the get method:


To go forward or backward in the tab history:


Keep in mind that this functionality is completely dependent on the driver used. You can get unexpected results if you are used to the behavior of a particular browser and work with another.

3.7. Cookies

Before we conclude this chapter, you may be interested in learning how to use cookies. First of all, you need a domain that uses cookies:

# Перейти на необходимый домен
# Установить куки. Следующий cookie действителен для всего домена
cookie = {"ключ": "значение"}
# И теперь получим все доступные куки для текущего адреса URL
all_cookies = driver.get_cookies()
for cookie_name, cookie_value in all_cookies.items():
    print("%s -> %s", cookie_name, cookie_value)

Go to next chapter

Also popular now: