Selenium import webdriver linux

Selenium для Python. Глава 1. Установка

Представляю перевод неофициальной документации Selenium для Python.
Перевод сделан с разрешения автора Baiju Muthukadan.
Оригинал можно найти здесь.

Предисловие от автора статьи

Selenium WebDriver – это программная библиотека для управления браузерами. WebDriver представляет собой драйверы для различных браузеров и клиентские библиотеки на разных языках программирования, предназначенные для управления этими драйверами.

По сути своей использование такого веб-драйвера сводится к созданию бота, выполняющего всю ручную работу с браузером автоматизированно.

Библиотеки WebDriver доступны на языках Java, .Net (C#), Python, Ruby, JavaScript, драйверы реализованы для браузеров Firefox, InternetExplorer, Safari, Andriod, iOS (а также Chrome и Opera).

Чаще всего Selenium WebDriver используется для тестирования функционала веб-сайтов/веб-ориентированных приложений. Автоматизированное тестирование удобно, потому что позволяет многократно запускать повторяющиеся тесты. Регрессионное тестирование, то есть, проверка, что старый код не перестал работать правильно после внесения новых изменений, является типичным примером, когда необходима автоматизация. WebDriver предоставляет все необходимые методы, обеспечивает высокую скорость теста и гарантирует корректность проверки (поскольку человеский фактор исключен). В официальной документации Selenium приводятся следующие плюсы автоматизированного тестирования веб-приложений:

  • возможность проводить чаще регрессионное тестирование;
  • быстрое предоставление разработчикам отчета о состоянии продукта;
  • получение потенциально бесконечного числа прогонов тестов;
  • обеспечение поддержки Agile и экстремальным методам разработки;
  • сохранение строгой документации тестов;
  • обнаружение ошибок, которые были пропущены на стадии ручного тестирования.

Функционал WebDriver позволяет использовать его не только для тестирования, но и для администрирования веб-сервисов, сократив до возможного предела количество действий, производимых вручную. Selenium WebDriver становится незаменимым помощником в случаях, когда, к примеру, ядро сайта устарело и требует от модераторов большого количества телодвижений для реализации маленьких фич (например, загрузки галереи фото).

Также одной из незаменимых особенностей Selenium WebDriver является ожидание загрузки страницы. Сюда можно отнести случаи, когда парсинг данных на странице невозможен из-за страниц перенаправления или ожидания, содержащих примерно такой текст: «Подождите, страница загружается». Такие страницы, само собой разумеется, не является целью парсинга, однако обойти их часто не представляется возможным. Естественно, без Selenium WebDriver. Selenium WebDriver позволяет в таких случаях «ожидать», как ожидал бы человек, пока на странице, к примеру, не появится элемент с необходимым именем.

Еще один плюс Selenium заключен в том, что действия веб-драйвера видимы визуально и требуют минимального времени нахождения на странице, это позволяет с удобством демонстрировать функционал сайта, когда необходима презентация сервиса.

Некоторые проблемы WebDriver (из сети и личного опыта):

  • бывает, что поведение отличается в разных браузерах;
  • иногда возникают сложности с поиском элементов (XPath и другие методы иногда просто не работают, хотя должны);
  • необъяснимые падения драйвера прямо посреди теста;
  • взаимодействие возможно только с первой вкладкой браузера, драйвер позволяет открывать новые вкладки и новые окна, но не позволяет в них работать;
  • необходимо четко продумывать архитектуру теста, часто использовать assert или ожидания, чтобы тест умел «думать», когда делать и когда нет.

Подробнее о проекте Selenium и серии их ПО можно прочитать здесь, либо в официальной документации или ее переводе.

Содержание:

1. Установка

1.1. Введение

Привязка Selenium к Python предоставляет собой простой API [Интерфейс программирования приложений (англ. Application Programming Interface) — Прим. пер.] для написания тестов функциональности/тестов соответствия требованиям с использованием веб-драйвера Selenium WebDriver. С помощью Selenium Python API вы можете интуитивно просто получить доступ ко всему функционалу Selenium WebDriver.

Привязка Python-Selenium предоставляет удобный API для доступа к таким веб-драйверам Selenium как Firefox, Ie, Chrome, Remote и других. На данный момент поддерживаются версии Python 2.7, 3.2, 3.3 и 3.4.

Читайте также:  Windows 10 подключить принтер для всех пользователей

В данной документации рассмотрен Selenium 2 WebDriver API. Selenium 1 / Selenium RC API в ней не охвачены.

1.2. Загрузка Selenium для Python

Для создания изолированной среды Python вы можете использовать virtualenv. Также библиотека Python 3.4 содержит модуль pyvenv, который практически аналогичен virtualenv.

1.3. Подробная инструкция для пользователей Windows

Примечание
Для данной инсталляции вам необходим доступ к сети Интернет.

1.4. Загрузка Selenium server

Примечание
Selenium server необходим в случаях, когда вы хотите использовать remote WebDriver [удаленный — Прим. пер.]. За дополнительной информацией обращайтесь к разделу Использование Selenium с remote WebDriver. Если вы только начинаете изучать Selenium, вы можете пропустить этот раздел и продолжить изучение со следующей главы.

Selenium server написан на языке Java. Для его запуска рекомендована среда Java Runtime Environment (JRE) версии 1.6 или выше.

Вы можете скачать Selenium server 2.x на странице загрузок сайта selenium. Имя файла должно выглядеть примерно таким образом: selenium-server-standalone-2.x.x.jar. Вы всегда можете загрузить последнюю версию Selenium server 2.x.

Если Java Runtime Environment (JRE) не установлена в вашей системе, вы можете скачать JRE с сайта Oracle. Если вы используете системы GNU/Linux и имеете права root [права администратора — Прим. пер.], вы так же можете установить JRE, используя инструкции вашей системы.

Если команда java доступна в PATH (переменная окружения), вы можете запустить Selenium server используя следующую команду:

Замените 2.x.x актуальной версией Selenium server, скачанной вами с сайта.

Если JRE установлена под пользователем, не обладающим правами root и/или если она недоступна в переменной окружения PATH, вы можете ввести относительный или полный путь до файла java. Аналогично, вы можете дополнить имя jar-файла Selenium server до относительного или полного пути. После этого команда будет выглядеть так:

Источник

2. Getting StartedВ¶

2.1. Simple UsageВ¶

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

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

The python which you are running should have the selenium module installed.

2.2. Example ExplainedВ¶

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.

Next, the instance of Firefox WebDriver is created.

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. Be aware that if your page uses a lot of AJAX on load then WebDriver may not know when it has completely loaded:

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

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. A detailed explanation of finding elements is available in the Locating Elements chapter:

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

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

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.:

2.3. Using Selenium to write testsВ¶

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 pytest and nose.

Читайте также:  C windows forms ввод пароля

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:

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

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 of arguments to the main function as shown below:

2.4. Walkthrough of the exampleВ¶

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 provides 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:

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.

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.

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. Be aware that if your page uses a lot of AJAX on load then WebDriver may not know when it has completely loaded:

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

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:

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 :

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

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.:

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

2.5. Using Selenium with remote WebDriverВ¶

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

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

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

The desired capabilities is a dictionary, so instead of using the default dictionaries, you can specify the values explicitly:

Источник

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.

Читайте также:  Электронная подпись для mac os

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. Installing Python bindings for SeleniumВ¶

Use pip to install the selenium package. Python 3 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. Instructions for Windows usersВ¶

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.4. 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.

1.5. 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/chromium.org/driver/
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.6. 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:

Источник

Оцените статью