Как установить selenium на windows

Время на прочтение5 мин

Количество просмотров502K

Представляю перевод неофициальной документации 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. Установка
2. Первые Шаги
3. Навигация
4. Поиск Элементов
5. Ожидания
6. Объекты Страницы
7. WebDriver API
8. Приложение: Часто Задаваемые Вопросы

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.

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

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

Вы можете загрузить привязку Selenium к Python со страницы пакета selenium на PyPI. Однако, лучшим способом будет использование модуля pip. Python 3.4 содержит pip в стандартной библиотеке. Используя pip, вы можете установить selenium следующей командой:

pip install selenium

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

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

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

1. Установите Python 3.4 через файл MSI, доступный на странице загрузок сайта python.org.
2. Запустите командную строку через программу cmd.exe и запустите команду pip установки selenium, как показано ниже.

C:\Python34\Scripts\pip.exe install selenium

Теперь вы можете запускать свои тестовые скрипты, используя Python. К примеру, если вы создали скрипт на основе Selenium и сохранили его в C:\my_selenium_script.py, то вы можете запустить его следующей командой:

C:\Python34\python.exe C:\my_selenium_script.py

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 используя следующую команду:

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

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

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

/путь/до/java -jar /путь/до/selenium-server-standalone-2.x.x.jar

Перейти к следующей главе

Python 2 предварительно установлен на Mac и большинстве дистрибутивов Linux. Для новых Python проектов рекомендуется Python 3, который был впервые выпущен в 2008 году.

Инструкции по установке Python в Windows

Загрузите последнюю версию программы установки и запустите ее.

Установка Python и Selenium

Для удобства используйте все параметры по умолчанию, кроме «Add python.exe to Path».

Установка Python на Mac

Установите Selenium-WebDriver для Python

PIP — это менеджер пакетов для Python. PIP поставляется с установщиком Python, Выполните следующую команду для обновления до последней версии PIP.

python m pip install upgrade pip

Установка Selenium-WebDriver для Python

Выполняем в терминал Windows, Linux или Mac

Результат

Collecting selenium

Downloading selenium3.0.2py2.py3noneany.whl (915kB)

100% |################################| 921kB 525kB/s

Installing collected packages: selenium

Successfully installed selenium3.0.2

Установка драйвера

Каждый браузер имеет свой собственный драйвер для Selenium. Мы подготовили нужную информацию для установки драйверов для каждого браузера.

Setting up the Selenium library for your favourite programming language.

First you need to install the Selenium bindings for your automation project.
The installation process for libraries depends on the language you choose to use.
Make sure you check the Selenium downloads page to make sure
you are using the latest version.

View the minimum supported Java version here.

Installation of Selenium libraries for Java is accomplished using a build tool.

Maven

Specify the dependencies in the project’s pom.xml file:

        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>${selenium.version}</version>
        </dependency>

Gradle

Specify the dependency in the project build.gradle file as testImplementation:

    testImplementation 'org.seleniumhq.selenium:selenium-java:4.31.0'
    testImplementation 'org.junit.jupiter:junit-jupiter-engine:5.12.1'

The minimum supported Python version for each Selenium version can be found
in “Supported Python Versions” on PyPi.

There are a couple different ways to install Selenium.

Pip

Download

Alternatively you can download the PyPI Built Distribution
(selenium-x.x.x.-py3-none-any.whl) and install it using pip:

pip install selenium-x.x.x.-py3-none-any.whl

Require in project

To use it in a project, add it to the requirements.txt file:

A list of all supported frameworks for each version of Selenium
is available on Nuget

There are a few options for installing Selenium.

Packet Manager

Install-Package Selenium.WebDriver

.NET CLI

dotnet add package Selenium.WebDriver

CSProj

in the project’s csproj file, specify the dependency as a PackageReference in ItemGroup:

      <PackageReference Include="Selenium.WebDriver" Version="4.31.0" />

Additional considerations

Further items of note for using Visual Studio Code (vscode) and C#

Install the compatible .NET SDK as per the section above.
Also install the vscode extensions (Ctrl-Shift-X) for C# and NuGet.
Follow the instruction here
to create and run the “Hello World” console project using C#.
You may also create a NUnit starter project using the command line dotnet new NUnit.
Make sure the file %appdata%\NuGet\nuget.config is configured properly as some developers reported that it will be empty due to some issues.
If nuget.config is empty, or not configured properly, then .NET builds will fail for Selenium Projects.
Add the following section to the file nuget.config if it is empty:

<configuration>
  <packageSources>
    <add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
    <add key="nuget.org" value="https://www.nuget.org/api/v2/" />   
  </packageSources>
...

For more info about nuget.config click here.
You may have to customize nuget.config to meet you needs.

Now, go back to vscode, press Ctrl-Shift-P, and type “NuGet Add Package”, and enter the required Selenium packages such as Selenium.WebDriver.
Press Enter and select the version.
Now you can use the examples in the documentation related to C# with vscode.

You can see the minimum required version of Ruby for any given Selenium version
on rubygems.org

Selenium can be installed two different ways.

Install manually

gem install selenium-webdriver

Add to project’s gemfile

gem 'selenium-devtools', '= 0.135.0'

You can find the minimum required version of Node for any given version of Selenium in the
Node Support Policy section on npmjs

Selenium is typically installed using npm.

Install locally

npm install selenium-webdriver

Add to project

In your project’s package.json, add requirement to dependencies:

Use the Java bindings for Kotlin.

You are here: Home / Basic Selenium / How To Install Selenium In Windows Step by Step

In this post, I will guide you on how you can Install Selenium In Windows in a simple guide. You just need an active internet connection and browser, rest everything is covered.

Before we start the process just want to highlight that Selenium supports multiple languages like Java, C#, Python, JavaScript, PHP etc. Here we will be covering with Java.

In case you want to automate application using Python or C# or JavaScript then I have dedicated videos on my channel and I will give you the links for reference.

Selenium with Python

Selenium with C#

Selenium with JavaScript

In order to use Selenium with Java, we need to make sure Java is installed in the Local System.

Note- I would recommend you to use Java 8 at this moment which is stable with all Selenium versions.

Step 1- Open command prompt and type java -version and make sure you get Java Version

Verify Java Installed

Step 2- Download your favorite editor like Eclipse, IntelliJ, NetBeans, etc. This post will focus on eclipse.

Download Eclipse for from their official website

https://eclipse.org/downloads/

Here you will get so many flavors of eclipse IDE you can select first which is coming to Eclipse IDE for Java Developers based on your requirement select 32 or 64 bit.

Here we will select 32-bit windows

Install Selenium In Windows

Install Selenium In Windows

Let’s wait for download window to appear, now click on OK button to start download

Install Selenium In Windows

Once download will finish, start to extract the zip file and wait for the extraction process to finish. It will take around 15 min to finish.

Install Selenium In Windows

Once the extraction process will finish you will get eclipse-standard folder

Install Selenium In Windows

Open eclipse folder

Install Selenium In Windows

Open Eclipse.exe

Install Selenium In Windows

We are done Configure Eclipse for Selenium

Install Selenium In Windows

Download Selenium Jars and add into the project

Selenium Webdriver is a collection of Java library with some predefined methods which help you to automate browsers. If any control goes out of the browser then Selenium will not be able to handle it.

Selenium Webdriver also is known as Selenium 3 and in future, you will get as Selenium 4

I also have a detailed video on complete installation which covers the installation of Java, Selenium.

In Java term collection of library is packed into jar files (Java Achieve file).

Step 1- Open any browser and navigate to  https://www.selenium.dev/downloads/

Step 2- Navigate to Selenium Server section

Step 3- We will also download the Selenium server, one jar is enough if you want to start the automation.

Selenium Jar download

Step 4-  Create a normal java project > Right click on Project > Click on build path > Click on configure build path >Click on library> Click on external jar> add the downloaded jar and click on Apply then ok button.

Now you can start automating application using Selenium.

Configure Eclipse with TestNG

You can also use one of the testing framework called TestNG which will offer different methods and classes which will help us create a robust framework. You can also use the JUnit framework as well but TestNG is more powerful than JUnit.

You can install in different ways

1- From Eclipse Marketplace

2- Using install new software section.

Open eclipse

Install Selenium In Windows

Eclipse home page

Step 2- In eclipse, we have some default plugin available now we will install external software into eclipse.
Click on Help then Install new software

Install Selenium In Windows

Click on help

Step 3-  We have to provide TestNG url so that eclipse can fetch TestNG plugin

Install Selenium In Windows

Specify the URL

Step 4- To get TestNG url please visit  http://testng.org/doc/download.html and copy the below mention URL and paste the same URL in Eclipse and Press Enter

Install Selenium In Windows

Copy download URL
Install Selenium In Windows

Select TestNG checkbox

Click on Next

Step 5- Accept the term &condition, and click on the finish button.

During installation, it will ask you to restart eclipse so please go-ahead to restart eclipse.

Install Selenium In Windows

Click on Finish.

Once everything is installed you can start Automation any application.

You can follow the below tutorial next to get started.

Next: How To Start Chrome Browser in Selenium

Next: How To Start Firefox Browser in Selenium

Next: How To Start IE Browser in Selenium

Automation has become an integrated part of the software development industry. Many frameworks have been developed that allow users to enhance their workflow by automating repetitive tasks with a few lines of code.

Selenium is one such tool that allows you to run automated tests on web applications. One notable component of the complete Selenium package is the Selenium WebDriver. In this article, we will provide a brief introduction to Selenium, along with a detailed guide on how you can install and setup Selenium WebDriver on your system.

What Is Selenium

Selenium is an open source automation testing framework that is primarily used to validate web apps on different browsers and platforms. The framework is available for a number of programming languages including Java, C#, Python, and Perl.

There are various components of the Selenium framework:

  1. Selenium IDE (Integrated Development Environment)
  2. Selenium Remote Control
  3. Selenium WebDriver
  4. Selenium Grid

All of these components have some distinct features associated with them. But in general, the whole Selenium framework helps in the automated testing of web applications.

In addition to web testing, you can develop web crawlers using the Selenium WebDriver as well.

Installing Selenium WebDriver

To install Selenium WebDriver, you need to have one of the supported languages installed on your computer. In this post, we will be focusing specifically on Python.

On Windows

First, you will have to install Python on your computer. Head over to the official Python download page and grab the latest version for Windows.

Download: Python for Windows

Then, install Selenium WebDriver using Pip, the official Python package manager. Type in the following command to install Selenium:

        pip install selenium
    

If the above command throws an error, you can execute the pip command using the -m flag. The -m flag stands for module name and allows you to pass a module at the time of invoking Python.

        python -m pip install selenium
    

On Linux

Installing Python on Linux is easy. All you need to do is download the official Python package using the default package manager of your distribution.

On Debian,

        sudo apt-get install python
    

On Arch,

        sudo pacman -S python
    

With Fedora,

        sudo dnf install python
    

On CentOS,

        sudo yum install python
    

Now, to install Selenium WebDriver, open your terminal and enter:

        pip install selenium
    

or

        python -m pip install selenium
    

On macOS

To install Python on your Mac, download the latest binary package from the official Python download page.

Download: Python for Mac

After installing Python, launch the terminal and type:

        pip install selenium
    

Alternatively, you can launch pip using the -m flag while invoking Python:

        python -m pip install selenium
    

How to Setup Selenium WebDriver With Python

In order to use Selenium WebDriver for web automation, you will have to download a driver that integrates with the browser of your choice. This driver will allow Selenium to control the browser and automate the commands that you write in your scripts.

Selenium currently supports Google Chrome, Firefox, Microsoft Edge, and Safari. The official webdriver for Chrome is the ChromeDriver, whereas Geckodriver is the official webdriver for Firefox.

Driver Name

Supported Browser

Download

ChromeDriver

Google Chrome

Download

GeckoDriver

Firefox

Download

WebDriver

Microsoft Edge

Download

WebDriver

Apple Safari

Download

Note that you will have to add the webdriver to your system’s PATH variables in order to use Selenium.

On Windows

To add the webdriver to PATH variables in Windows:

  1. Download the webdriver of your choice from the aforementioned link
  2. Extract the downloaded ZIP file and copy the webdrivername file to a specific location on your local storage
  3. Now, copy the path of the executable file
  4. Open This PC and right-click on the empty area, selecting Properties from the list of options

    my computer properties

  5. Click on the Change Settings option.

    change windows settings

  6. Switch to the Advanced tab and click Environment variables

    environment variables settings

  7. Under System Variables, scroll down until you find an entry titled Path
  8. Highlight that entry and click on Edit

    edit the path variable

  9. Click on the New button and type in the path of the webdriver in the respective field

    add new path variable

  10. Click on OK to save the settings

To check if the driver is installed properly, launch a new Command Prompt window and enter the name of the webdriver. For example, if you are using ChromeDriver, type in chromedriver and press Enter.

If the driver is not installed properly, an error will occur.

        'chromedriver' is not recognized as an internal or external command,
operable program or batch file.

Configure the Webdriver PATH Variable on Linux

To add the webdriver to PATH variables on Linux:

  1. Download the webdriver for Linux using the link mentioned above
  2. Extract the downloaded ZIP file and copy the webdrivername file to a specific location on your system storage
  3. Now, copy the path of the executable file
  4. Launch the terminal by pressing Ctrl + Alt + T
  5. Edit the user profile file—while you can open the file with any Linux text editor of your choice, in this case, we will be using Nano

            sudo nano /home/username/.profile
        
  6. Append the following line to the end of the file

            export PATH=$PATH:/pathtodriver/webdriver
        
  7. Save the file

On macOS

Setting up the webdriver on a macOS device is easy. To do this:

  1. Download the webdriver for Linux using the links mentioned above
  2. Extract the downloaded ZIP file and copy the webdrivername file to a specific location on your system storage
  3. Now, copy the path of the executable file
  4. Open up the terminal
  5. Edit the paths file on your system by entering the command given below

            sudo nano /etc/paths
        
  6. Enter your system password for verification
  7. Paste the path of the webdriver at the end of the file
  8. Save the file and quit

You can check if the webdriver is installed properly by typing the name of the webdriver in the terminal.

Automating a Browser With Selenium WebDriver

With the power of Selenium, browser automation has never been easier. You can automate some basic repetitive tasks yourself by simply writing a piece of code. Cybersecurity analysts can benefit as well by automating web penetration testing using Selenium.

Although Selenium is the first choice of many developers who frequently test web applications, there are some other testing frameworks as well that are worth a try.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Не загружается windows 10 диагностика компьютера
  • Список общих папок windows
  • Canon 1133a драйвер сканера windows 10 x64
  • Как вернуть стандартные иконки на windows 10
  • Https solutions brother com windows