Установка selenium python на windows

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. Мы подготовили нужную информацию для установки драйверов для каждого браузера.

Supported Python Versions¶

  • Python 3.8+

Installing¶

If you have pip on your system, you can simply install or upgrade the Python bindings:

Alternately, you can download the source distribution from PyPI <https://pypi.org/project/selenium/#files>, unarchive it, and run:

Note: You may want to consider using virtualenv to create isolated Python environments.

Example 0:¶

  • open a new Firefox browser
  • load the page at the given URL
from selenium import webdriver

browser = webdriver.Firefox()
browser.get('http://selenium.dev/')

Example 1:¶

  • open a new Firefox browser
  • load the Yahoo homepage
  • search for “seleniumhq”
  • close the browser
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys

browser = webdriver.Firefox()

browser.get('http://www.yahoo.com')
assert 'Yahoo' in browser.title

elem = browser.find_element(By.NAME, 'p')  # Find the search box
elem.send_keys('seleniumhq' + Keys.RETURN)

browser.quit()

Example 2:¶

Selenium WebDriver is often used as a basis for testing web applications. Here is a simple example using Python’s standard unittest library:

import unittest
from selenium import webdriver

class GoogleTestCase(unittest.TestCase):

    def setUp(self):
        self.browser = webdriver.Firefox()
        self.addCleanup(self.browser.quit)

    def test_page_title(self):
        self.browser.get('http://www.google.com')
        self.assertIn('Google', self.browser.title)

if __name__ == '__main__':
    unittest.main(verbosity=2)

Selenium Server (optional)¶

For normal WebDriver scripts (non-Remote), the Java server is not needed.

However, to use Selenium Webdriver Remote , you need to also run the Selenium server. The server requires a Java Runtime Environment (JRE).

Download the server separately, from: https://www.selenium.dev/downloads/

Run the server from the command line:

java -jar selenium-server-4.14.0.jar

Then run your Python client scripts.

Contributing¶

  • Create a branch for your work
  • Ensure tox is installed (using a virtualenv is recommended)
  • python3.8 -m venv .venv && . .venv/bin/activate && pip install tox
  • After making changes, before committing execute tox -e linting
  • If tox exits 0, commit and push otherwise fix the newly introduced breakages.
  • flake8 requires manual fixes
  • black will often rewrite the breakages automatically, however the files are unstaged and should staged again.
  • isort will often rewrite the breakages automatically, however the files are unstaged and should staged again.

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

  1. Install Python 3 using the MSI available in python.org download page.

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

    C:\Python39\Scripts\pip.exe 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:

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

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.

Note

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:

bazel //py:selenium-wheel

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.

Starting from version 4.6.0 (November 4, 2022)
selenium comes with Selenium Manager packed in distribution.

Selenium Manager is a new tool that helps to get a working environment
to run Selenium out of the box:

  • automatically discovers, downloads, and caches the drivers
    required by Selenium when these drivers are unavailable;
  • automatically discovers, downloads, and caches the browsers
    driven with Selenium (Chrome, Firefox, and Edge)
    when these browsers are not installed in the local system.

For example, to see the result of Selenium Manager work
just run any selenium script without previous driver setup
and explore ~/.cache/selenium.

More about Selenium Manager you can read in the
documentation
and
blog.

1.6. Downloading Selenium server¶

Note

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

/path/to/java -jar /path/to/selenium-server-standalone-2.x.x.jar

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

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

Представляю перевод неофициальной документации 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

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

Introduction

Python language bindings for Selenium WebDriver.

The selenium package is used to automate web browser interaction from Python.

Several browsers/drivers are supported (Firefox, Chrome, Internet Explorer), as well as the Remote protocol.

Supported Python Versions

  • Python 3.8+

Installing

If you have pip on your system, you can simply install or upgrade the Python bindings:

pip install -U selenium

Alternately, you can download the source distribution from PyPI <https://pypi.org/project/selenium/#files>, unarchive it, and run:

python setup.py install

Note: You may want to consider using virtualenv to create isolated Python environments.

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.

Example 0:

  • open a new Firefox browser

  • load the page at the given URL

from selenium import webdriver

browser = webdriver.Firefox()
browser.get('http://selenium.dev/')

Example 1:

  • open a new Firefox browser

  • load the Yahoo homepage

  • search for “seleniumhq”

  • close the browser

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys

browser = webdriver.Firefox()

browser.get('http://www.yahoo.com')
assert 'Yahoo' in browser.title

elem = browser.find_element(By.NAME, 'p')  # Find the search box
elem.send_keys('seleniumhq' + Keys.RETURN)

browser.quit()

Example 2:

Selenium WebDriver is often used as a basis for testing web applications. Here is a simple example using Python’s standard unittest library:

import unittest
from selenium import webdriver

class GoogleTestCase(unittest.TestCase):

    def setUp(self):
        self.browser = webdriver.Firefox()
        self.addCleanup(self.browser.quit)

    def test_page_title(self):
        self.browser.get('http://www.google.com')
        self.assertIn('Google', self.browser.title)

if __name__ == '__main__':
    unittest.main(verbosity=2)

Selenium Server (optional)

For normal WebDriver scripts (non-Remote), the Java server is not needed.

However, to use Selenium Webdriver Remote , you need to also run the Selenium server. The server requires a Java Runtime Environment (JRE).

Download the server separately, from: https://www.selenium.dev/downloads/

Run the server from the command line:

java -jar selenium-server-4.14.0.jar

Then run your Python client scripts.

Use The Source Luke!

View source code online:

Contributing

  • Create a branch for your work

  • Ensure tox is installed (using a virtualenv is recommended)

  • python3.8 -m venv .venv && . .venv/bin/activate && pip install tox

  • After making changes, before committing execute tox -e linting

  • If tox exits 0, commit and push otherwise fix the newly introduced breakages.

  • flake8 requires manual fixes

  • black will often rewrite the breakages automatically, however the files are unstaged and should staged again.

  • isort will often rewrite the breakages automatically, however the files are unstaged and should staged again.

  • Установка virtio драйверов в windows
  • Установка windows 10 pro с диска
  • Установка windows 10 как выбрать диск для установки
  • Установка windows 10 на ssd gpt или mbr
  • Установка oracle на windows 7 x64