Install selenium on windows

Downloads

Below is where you can find the latest releases of all the Selenium components. You can also find a list of previous releases, source code, and additional information for Maven users.

Selenium Server (Grid)

The Selenium Server is needed in order to run Remote Selenium WebDriver (Grid).

Latest stable version 3.141.59

To use the Selenium Server in a Grid configuration see the documentation.

Latest Selenium 4 Beta version 4.0.0-beta-3

The Internet Explorer Driver Server

This is required if you want to make use of the latest and greatest features of the WebDriver InternetExplorerDriver.
Please make sure that this is available on your $PATH (or %PATH% on Windows) in order for the IE Driver to work as expected.

Selenium Client & WebDriver Language Bindings

In order to create scripts that interact with the Selenium Server (Remote WebDriver) or create local Selenium WebDriver scripts, you need to make use of language-specific client drivers.

While language bindings for other languages exist, these are the core ones that are supported by the main project hosted on GitHub.

Language Stable Version Release Date Beta Version Beta Release Date Links
Ruby 3.142.6 October 04, 2019 4.0.0beta3 April 13, 2021 Download Beta Download Changelog API Docs
Java 3.141.59 November 14, 2018 4.0.0-beta-3 April 13, 2021 Download Beta Download Changelog API Docs
Python 3.141.0 November 01, 2018 4.0.0.b3 April 13, 2021 Download Beta Download Changelog API Docs
C# 3.14.0 August 02, 2018 4.0.0-beta2 March 17, 2021 Download Beta Download Changelog API Docs
JavaScript 3.6.0 October 06, 2017 4.0.0-beta.3 April 13, 2021 Download Beta Download Changelog API Docs

C# NuGet

Nuget latest release is 3.14.0. Released on 2018-08-02

Selenium IDE

Selenium IDE is a Chrome and Firefox plugin which records and plays back user interactions with the browser. Use this to either create simple scripts or assist in exploratory testing.

Download latest released version for Chrome or for Firefox or view the Release Notes.

Maven Information

If you’re using Maven, you will find more information here.

Third Party Drivers, Bindings, and Plugins

Selenium can be extended through the use of plugins.
Here are a number of plugins created and maintained by third parties. For more information on how to create your own plugin or have it listed, learn more here.

Platforms Supported by Selenium

Firefox

GeckoDriver is implemented and supported by Mozilla, refer to their documentation for supported versions.

Internet Explorer

Only version 11 is supported, and it requires additional configuration.

Safari

SafariDriver is supported directly by Apple, for more information, check their documentation

Opera

OperaDriver is supported by Opera Software, refer to their documentation for supported versions.

Chrome

ChromeDriver is supported by the Chromium project, please refer to their documentation for any compatibility information

Microsoft is implementing and maintaining the Microsoft Edge WebDriver, please refer to their documentation for any compatibility information

Microsoft Windows

Most versions of MS Windows that are currently still supported by Microsoft should work with Selenium. Although we use the latest MS Windows to troubleshoot things, it does not mean Selenium won’t attempt to support different versions of Windows. This only means we don’t continually run tests on other particular version of Windows.

macOS

We currently do not use any version of macOS in our automated tests against the selenium project. However most developers on the project are using a recent version of macOS and we’ll continue to support the current stable release and often the previous release.

Linux

We test mainly on Ubuntu, but other variations of Linux should also work where the browser manufacturers support them.

Source Code

You can also find a list of the Selenium source code at our GitHub repository here.

1. InstallationВ¶

1.1. IntroductionВ¶

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.

Selenium Python bindings provide a convenient API to access Selenium WebDrivers like Firefox, Ie, Chrome, Remote etc. The current supported Python versions are 3.5 and above.

This documentation explains Selenium 2 WebDriver API. Selenium 1 / Selenium RC API is not covered here.

1.2. Downloading Python bindings for SeleniumВ¶

Use pip to install the selenium package. Python 3.6 has pip available in the standard library. Using pip , you can install selenium like this:

You may consider using virtualenv to create isolated Python environments. Python 3 has venv which is almost the same as virtualenv.

You can also download Python bindings for Selenium from the PyPI page for selenium package. and install manually.

1.3. DriversВ¶

Selenium requires a driver to interface with the chosen browser. Firefox, for example, requires geckodriver, which needs to be installed before the below examples can be run. Make sure it’s in your PATH , e. g., place it in /usr/bin or /usr/local/bin .

Failure to observe this step will give you an error selenium.common.exceptions.WebDriverException: Message: ‘geckodriver’ executable needs to be in PATH.

Other supported browsers will have their own drivers available. Links to some of the more popular browser drivers follow.

Chrome: https://sites.google.com/a/chromium.org/chromedriver/downloads
Edge: https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/
Firefox: https://github.com/mozilla/geckodriver/releases
Safari: https://webkit.org/blog/6900/webdriver-support-in-safari-10/

For more information about driver installation, please refer the official documentation.

1.4. Detailed instructions for Windows usersВ¶

You should have an internet connection to perform this installation.

Start a command prompt using the cmd.exe program and run the pip command as given below to install selenium .

Now you can run your test scripts using Python. For example, if you have created a Selenium based script and saved it inside C:\my_selenium_script.py , you can run it like this:

1.5. Downloading Selenium serverВ¶

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:

Replace 2.x.x with the 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 a relative or absolute path to Selenium server jar file. Then, the command will look something like this:

1.6. Installing from Git sourcesВ¶

To build Selenium Python from the source code, clone the official repository. It contains the source code for all official Selenium flavors, like Python, Java, Ruby and others. The Python code resides in the /py directory. To build, you will also need the Bazel build system.

Currently, as Selenium gets near to the 4.0.0 release, it requires Bazel 3.2.0 (Install instructions), even though 3.3.0 is already available.

To build a Wheel from the sources, run the following command from the repository root:

This command will prepare the source code with some preprocessed JS files needed by some webdriver modules and build the .whl package inside the ./bazel-bin/py/ directory. Afterwards, you can use pip to install it.

Install selenium on windows

Что пишут в блогах

В этом выпуске говорили о новостях мира тестирования за март 2021: книги, полезные материалы и новые релизы инструментов, которые будут полезны для тестировщиков разного уровня.

Онлайн-тренинги

Конференции

Что пишут в блогах (EN)

Разделы портала

Про инструменты

Автор: Энди Найт (Andy Knight)
Оригинал статьи
Перевод : Ольга Алифанова

Теперь, когда наш тест-проект создан, напишем несколько Web UI-тестов при помощи Selenium WebDriver!

Что такое WebDriver?

WebDriver – это программируемый интерфейс для взаимодействия с живыми веб-браузерами. Он позволяет тест-автоматизации открывать браузер, передавать клики, вводить символы, удалять текст, и чисто завершать работу с браузером. Интерфейс WebDriver рекомендован W3C. Самый популярный вариант реализации стандартов WebDriver – это Selenium WebDriver, бесплатный инструмент с открытым исходным кодом.

У WebDriver несколько компонентов:

  1. Языковые комплекты. Программные пакеты вроде Selenium WebDriver предоставляют комплекты языков программирования для взаимодействия с браузером. Selenium поддерживает основные языки вроде C#, Java, JavaScript, Ruby и Python.
  2. Код автоматизации. Программисты используют языковые комплекты для автоматизации взаимодействий с браузером. Распространенные взаимодействия – это, например, поиск элементов, клик по ним, и очищение текста. Обычно это пишется при помощи фреймворка тест-автоматизации.
  3. ПротоколJSONWire. Языковые комплекты кодируют любые взаимодействия, используя JSON, и отправляют их как запросы REST API к драйверу браузера. Протокол JSON Wire независим от языка и платформы.
  4. Драйвер браузера. Драйвер – это самостоятельный исполняемый модуль на тест-машине. Он работает как прокси между функцией, вызывающей взаимодействие, и браузером. Он получает запросы JSON для взаимодействий и отправляет их в браузер через HTTP.
  5. Браузер. Браузер обрабатывает тестируемые веб-страницы. Он в основном контролируется драйвером. Все основные браузеры поддерживают WebDriver, но каждому также нужен свой собственный тип драйвера, установленный на той же машине, что и браузер, и доступный по системному пути. К примеру, Google Chrome требует ChromeDriver.

Установка Selenium WebDriver

Для нашего тест-проекта мы будем использовать Python-комплекты Selenium WebDriver, а также Google Chrome и ChromeDriver. Можно пользоваться любым браузером, но давайте возьмем Chrome – у него, во-первых, очень высокая доля рынка, а во-вторых, есть инструменты разработчика, которые пригодятся позднее.

Убедитесь, что на вашей машине установлена самая свежая версия Chrome (для проверки и обновления Chrome перейдите в меню и выберите Help > About Google Chrome. Другой вариант – загрузите и установите его отсюда). Затем скачайте подходящую версию ChromeDriver тут и добавьте его в ваши системные пути.

Убедитесь, что СhromeDriver работает из командной строки:

  1. $ chromedriver
  2. Starting ChromeDriver 73.0.3683.68 (47787ec04b6e38e22703e856e101e840b65afe72) on port 9515
  3. Only local connections are allowed.
  4. Please protect ports used by ChromeDriver and related test frameworks to prevent access by malicious code.

Затем установите пакет Selenium Python в наше окружение:

  1. $ pipenv install selenium —dev

Теперь машина готова для веб-тестирования!

Новые тесты

Создайте новый модуль Python в директории tests/ по имени test_web.py. Этот новый модуль будет содержать наши Web UI-тесты. Теперь добавьте следующие импорты:

  1. import pytest
  2. from selenium.webdriver import Chrome
  3. from selenium.webdriver.common.keys import Keys

Зачем они нам нужны?

  • pytest будет использоваться для фикстур
  • Chrome предоставляет комплект ChromeDriver.
  • Keys содержат специальные нажатия клавиш для браузерных взаимодействий.

Настройка и очистка WebDriver

Хорошая практика – когда каждый тест-кейс использует собственную копию WebDriver. Настройка и очистка добавляют несколько секунд к каждому тесту, однако отдельная копия для каждого теста сохраняет их простоту, безопасность и независимость. Если один тест наткнется на проблему, это не затронет другие тесты. К тому же использование отдельной копии WebDriver для каждого теста позволяет запускать их параллельно.

Лучше всего настраивать WebDriver при помощи фикстуры pytest. Фикстуры – это модные функции pytest для настройки и очистки, а еще они умеют внедрять зависимости. Любой тест, требующий копии WebDriver, может просто вызвать фикстуру для его получения.

Код

Добавьте вот такой код в tests/test_web.py:

  1. @pytest.fixture
  2. def browser():
  3. driver = Chrome()
  4. driver.implicitly_wait(10)
  5. yield driver
  6. driver.quit()

browser – это фикстурная функция pytest, как указано в декораторе @pytest.fixture. Давайте рассмотрим каждую строчку, чтобы понимать, что делает эта новая фикстура.

Строки

Chrome() инициализирует копию ChromeDriver на локальной машине, используя настройки по умолчанию. Возвращенный объект драйвера привязан к копии ChromeDriver. Все вызовы WebDriver будут выполняться через него.

Самая болезненная часть тест-автоматизации Web UI – это ожидание загрузки или изменения страницы после инициации взаимодействия. Странице нужно время на обработку новых элементов, и если автотест попытается получить доступ к новым элементам до того, как они начнут существовать, WebDriver выдаст исключение NoSuchElementException. Неправильное ожидание – богатый источник «нестабильности» Web UI-тестов.

Метод implicitly_wait говорит драйверу подождать существования элементов не более 10 секунд, прежде чем пытаться их найти. Механизм ожидания довольно умен – вместо того, чтобы спать полные 10 секунд, он прекратит ожидание сразу после появления элемента. Неявные ожидания декларируются один раз, и затем автоматически используются для всех элементов. В отличие от них, явные ожидания могут быть заданы отдельно для каждого взаимодействия – ценой необходимости явных вызовов ожидания. Хорошая практика – использовать один стиль ожидания эксклюзивно для тест-автоматизации. Смешивание явных и неявных ожиданий может иметь мерзкие и неожиданные побочные эффекты. Для нашего проекта неявное 10-секундное ожидание должно быть достаточным (если у вас медленное Интернет-соединение, повысьте этот таймаут для компенсации).

Фикстура pytest должна возвращать значение, сообщающее, что именно настраивалось. Наша фикстура возвращает ссылку на инициализированный WebDriver. Однако вместо выражения return она использует yield, что означает, что фикстура – генератор. Первая итерация фикстуры – в нашем случае, инициализация WebDriver – это фаза «настройки», которая вызывается до того, как начался тест. Вторая итерация – вызов выхода – это фаза очистки, вызывающаяся после завершения теста. Запись фикстур как генераторов объединяет в одно целое связанные операции настройки и очистки.

Всегда выходите из копии WebDriver в конце теста, что бы ни случилось. Процессы драйвера на тест-машине не всегда умирают после окончания автоматизации. Отсутствие явного выхода из копии драйвера может оставить его запущенным как зомби-процесс – а это может привести к потреблению и даже блокировке системных ресурсов.

Читайте также:  Ночной режим для linux
Оцените статью