Как установить geckodriver windows
Как установить Geckodriver?
Я пытаюсь работать с Selenium в Python. Тем не менее, я не знаю, что делать, учитывая нижеприведенное на https://pypi.python.org/pypi/selenium
Я использую Windows 7 32bit. Я нашел geckodriver здесь: https://github.com/mozilla/geckodriver/releases
В основном я использовал дистрибутив Anaconda Python для работы с Excel, поэтому я не знаю, что такое «PATH»
ОБНОВЛЕНИЕ:
Я обновил PATH, как показано в комментариях. Вот полная трассировка ошибок.
Microsoft Windows [Версия 6.1.7601] Copyright (c) 2009 Корпорация Microsoft. Все права защищены.
Python 3.5.2 | Anaconda 4.2.0 (32-разрядная версия) | (по умолчанию, 5 июля 2016, 11:45:57) [MSC v.1 900 32 бит (Intel)] на win32
Введите «помощь», «авторское право», «кредиты» или «лицензия» для получения дополнительной информации.
Traceback (последний вызов последний):
Файл «C:\Users\user1\AppData\Local\Continuum\Anaconda3\lib\subp rocess.py», строка 947, в init restore_signals, start_new_session)
Файл «C:\Users\user1\AppData\Local\Continuum\Anaconda3\lib\subp rocess.py», строка 1224, в _execute_child startupinfo)
FileNotFoundError: [WinError 2] Системе не удается найти указанный файл
ОТВЕТЫ
Ответ 1
Это будет успешно выполнено.
Ответ 2
Некоторые параметры, выберите 1:
в основном перетащите geckodriver где-нибудь там, где у вас есть свои исполняемые файлы, вы должны затем открыть командную строку и использовать ее.
/bin в linux и C:\Program Files
в частности объяснения о том, как видно водителя, где он может быть поставлен, и как изменить способ поиска селена.
Ответ 3
Самый простой способ, если вы находитесь на окнах:
Ответ 4
На момент написания статьи я выбрал последнюю версию, которая была просто версией, указанной в верхней части страницы. Для меня это был v0.24.0.
Прокрутите вниз до ресурсов, а затем нажмите и загрузите нужный драйвер. Для Windows это будет ZIP файл. Скорее всего 64бит. Загрузите веб-драйвер, нажав на ссылку 5. Щелкните правой кнопкой мыши на загруженном файле и разархивируйте файл.
Скопируйте и вставьте файл куда-нибудь в каталог python. Например, если я установил Python в C:\Python\Python37, я вставил бы туда файл, чтобы gecko находился в C:\Python\Python37\geckodriver-v0.24.0-win64.
Внутри этой папки, которую вы только что скопировали, будет geckodriver.exe
В Windows 10 нажмите кнопку «Windows» и найдите «переменные среды». Найдите переменные среды ИЛИ найдите их, используя эти инструкции; https://www.computerhope.com/issues/ch000549.htm
Нажмите на поле «переменные среды» в правом нижнем углу.
В нижнем поле «Системные переменные» выделите переменную «Path» следующим образом. Добавление переменной среды Path
Нажмите edit, а затем добавьте запись внизу списка. Скопируйте и вставьте папку, в которой находится файл geckodriver.exe. Для меня это был C:\Python\Python37\geckodriver-v0.24.0-win64 (или куда вы скопировали файл на шаге 6) Добавление геккона в Windows PATH
Ответ 5
Для меня это сработало (Windows 10, браузер Firefox):
Firefox до 46 версии поставляется с поддержкой WebDriver. Geckodriver требуется для Firefox выше 47+ версии. Нужно установить geckodriver отдельно от браузера.
Скачать geckodriver для Linux, Windows и Mac
Зайдите на github страницу с релизами чтобы выбрать нужный вам файл для скачивания в зависимости от вашей операционной системы и версии браузера Firefox.
На текущий момент, актуальная версия geckodriver является v0.26.0.
Установка geckodriver под Ubuntu, Windows и Mac
Ниже мы приводим примеры более «правильной» установки драйвера, но есть и более быстрый способ. Примените данный метод в двух случаях.
Инструкция установки
Если у вас Linux дистрибутив или Mac, вам нужно дать файлу geckodriver нужные права на выполнения. Открываем терминал и вводим команды одна за другой.
Теперь, когда вы будете запускать код в Python, вы должны указать Selenium на этот файл.
Для Windows
Минусы такого подхода
Установка geckodriver в Ubuntu, Debian и ArchLinux
Выбираем (в зависимости от архитектуры процессора x32 или x64) нужный tar архив. В моем случае будет файл geckodriver-v0.26.0-linux64.tar.gz у меня Ubuntu 18.04.3 LTS.
Вытаскиваем файл из архива.
Даем нужные права драйверу.
Отправляем драйвер в папку где его будет искать Selenium.
Установка geckodriver в Mac OS
Пожалуй, самая простая установка в Mac. Выполняем в терминале:
Проблема такого подхода в том, что может быть старая версия. Для новой версии смотрите на страницу github с релизами и скачиваем архив geckodriver-v0.26.0-macos.tar.gz.
Заходим через терминал в папку где будет лежать архив и сам драйвер.
Даем драйверу права на выполнения.
/.bashrc» с помощью VIM или NANO.
Добавляем в конец файла следующие строки. ВНИМАНИЕ! Заменяем «/your/path/» указывая реальный путь к geckodriver файлу.
Возможно вы не поймете как выйти из VIM. Такое бывает.
Теперь у вас будет последняя версия geckodriver на вашем новеньком маке.
Установка geckodriver в Windows
Windows пользователи возможно не слышали о таким виде архивов как tar.gz это нормально. Скачиваем и устанавливаем программу 7-Zip.
Программа для распаковки tar.gz в Windows: http://www.7-zip.org/
Полная инструкция по установки geckodriver в Windows показана в видео. Смотрим с 40 секунды и повторяем. Помните что не нужно скачивать именно ту версию, что указана в видео. По указанной ссылке с github последняя версия 0.19.1 когда в самом видео 12-я версия. Скачивайте самую новую версию, возможно когда вы сейчас читаете эту статью уже вышла новая версия — скачиваем её.
Скрипт теста ниже откроет веб-сайт в новом окне Firefox.
Как установить Geckodriver в системе Windows
Я пытаюсь установить webdriver, и чтобы открыть firefox, мне нужно установить geckodriver и указать правильный путь.
Во-первых, ссылка на скачивание для установки geckodriver позволяет только установить файл, который не является исполняемым файлом. Так есть ли способ сделать его исполняемым?
Во-вторых, я попытался изменить переменные пути в командной строке, но, конечно, это не сработало. Затем я изменил пользовательскую переменную, а не системные переменные пути, потому что в системе нет пути. В пользовательских переменных есть Path, так что я отредактировал его, чтобы изменить местоположение файла.
Я распаковал файл geckodriver rar и получил файл без расширения. Я не знаю, как вы можете получить файл без расширения, но они сделали это. Значок похож на чистый лист бумаги со сгибом вверху слева.
Если у кого-то есть решение для этого, включая, возможно, другой пакет, похожий на webdriver, который позволит мне открыть браузер и затем обновить страницу через определенное время. это все, что я хочу сделать.
4 ответа
Во-первых, убедитесь, что вы загружаете тот для вашей ОС. Windows находится внизу списка и будет называться win32. Загрузите этот файл или 64 не имеет значения.
Вы можете положить его где угодно. 1. положить его в папку вашего проекта. 2. создайте папку и вставьте в нее драйвер. Установите путь к драйверу в вашем коде.
Я боролся с тем же вопросом в течение последнего часа и наконец нашел решение, которое, надеюсь, поможет кому-то там (Windows 10, Python 2.7, дистрибутив Anaconda).
1) Это была проблема в моем случае: убедитесь, что у вас установлена последняя версия Firefox. У меня был Firefox 36, который при проверке обновлений говорил, что это последняя версия. На веб-сайте Mozilla была последняя версия 54. Так что загрузите Firefox с сайта и переустановите
2) Убедитесь, что у вас последняя версия geckodriver
Сначала загрузите GeckoDriver для Windows, распакуйте его и скопируйте путь к папке.
Install browser drivers
Through WebDriver, Selenium supports all major browsers on the market such as Chrom(ium), Firefox, Internet Explorer, Edge, Opera, and Safari. Where possible, WebDriver drives the browser using the browser’s built-in support for automation.
Since all the driver implementations except for Internet Explorer are provided by the browser vendors themselves, they are not included in the standard Selenium distribution. This section explains the basic requirements for getting you started with the different browsers.
Read about more advanced options in our Capabilities documentation.
Quick Reference
Browser | Supported OS | Maintained by | Download | Issue Tracker |
---|---|---|---|---|
Chromium/Chrome | Windows/macOS/Linux | Downloads | Issues | |
Firefox | Windows/macOS/Linux | Mozilla | Downloads | Issues |
Edge | Windows/macOS | Microsoft | Downloads | Via Browser |
Internet Explorer | Windows | Selenium Project | Downloads | Issues |
Safari | macOS High Sierra and newer | Apple | Built in | Issues |
Opera | Windows/macOS/Linux | Opera | Downloads | Issues |
Three Ways to Use Drivers
1. Driver Management Software
Most machines automatically update the browser, but the driver does not. To make sure you get the correct driver for your browser, there are many third party libraries to assist you.
2. The PATH Environment Variable
This option first requires manually downloading the driver (See Quick Reference Section for links).
This is a flexible option to change location of drivers without having to update your code, and will work on multiple machines without requiring that each machine put the drivers in the same place.
You can regain control of your command prompt by pressing Ctrl+C
3. Hard Coded Location
Similar to Option 2 above, you need to manually download the driver (See Quick Reference Section for links). Specifying the location in the code itself has the advantage of not needing to figure out Environment Variables on your system, but has the drawback of making the code much less flexible.
Starting Browsers
Chromium/Chrome
By default, Selenium 4 is compatible with Chrome v75 and greater. Note that the version of Chrome and the version of chromedriver must match the major version. See the Quick Reference Section for the applicable download link.
Examples for how to start Chrome are provided in the previous section detailing the Three Ways to Use Drivers.
Microsoft Edge is implemented with Chromium, with the earliest supported version of v79. Similar to Chrome, the version of Edge and the version of edgedriver must match the major version. See the Quick Reference Section for the applicable download link.
Firefox
Selenium 4 requires Firefox 78 or greater. It is recommended to always use the latest version of geckodriver. See the Quick Reference Section for the applicable download link.
Internet Explorer
The Selenium project aims to support the same releases that Microsoft considers current. Older releases may work, but will not be supported. Note that Internet Explorer 11 will end support for certain operating systems, including Windows 10 on June 15, 2022. Edge has an IE Compatibility mode that will continue to be supported.
The IE Driver is the only driver maintained by the Selenium Project directly. While binaries for both the 32-bit and 64-bit versions of Internet Explorer are available, there are some limitations with the 64-bit driver. As such it is recommended to use the 32-bit driver. It should be noted that as Internet Explorer preferences are saved against the logged in user’s account, some additional setup is required.
Additional information about using Internet Explorer can be found on the Selenium wiki, and you can see the Quick Reference Section for the applicable download link.
Opera
Current releases of Opera are built on top of the Chromium engine, and WebDriver is now supported via the closed-source Opera Chromium Driver.
Safari
Unlike Chromium and Firefox drivers, the safaridriver is installed with the Operating System. To enable automation on Safari, run the following command from the terminal:
Those looking to automate Safari on iOS should look to the Appium project.
Selenium Level Sponsors
Support the Selenium Project
Want to support the Selenium project? Learn more or view the full list of sponsors.
v0.26.0
Note that with this release the minimum recommended Firefox version
has changed to Firefox ≥60.
Known problems
macOS 10.15 (Catalina):
Due to the recent requirement from Apple that all programs must
be notarized, geckodriver will not work on Catalina if you manually
download it through another notarized program, such as Firefox.
Whilst we are working on a repackaging fix for this problem, you
can find more details on how to work around this issue in the
macOS notarization section of the documentation.
You must still have the Microsoft Visual Studio redistributable
runtime installed on your system for the binary to run. This
is a known bug which we weren’t able fix for this release.
In some cases geckodriver could crash due to a stack overflow when handling
certain device errors.
Added
Support for Firefox on Android
Starting with this release geckodriver is able to connect to
Firefox on Android systems, and to control packages based on
GeckoView.
Support for Android works by the geckodriver process running on
a host system and Firefox running within either an emulator or
on a physical device connected to the host system. This requires
you to first enable remote debugging on the Android device.
The WebDriver client must set the platformName capability to
» android » and the androidPackage capability within
moz:firefoxOptions to the Android package name of the Firefox
application.
The full list of new capabilities specific to Android, instructions
how to use them, and examples can be found in the moz:firefoxOptions
documentation on MDN.
When the session is created, the platformName capability will
return » android » instead of reporting the platform of the host
system.
Changed
Continued Marionette refactoring changes
0.25.0 came with a series of internal changes for how geckodriver
communicates with Firefox over the Marionette protocol. This
release contains the second half of the refactoring work.
Fixed
Connection attempts to Firefox made more reliable
geckodriver now waits for the Marionette handshake before assuming
the session has been established. This should improve reliability
in creating new WebDriver sessions.
Corrected error codes used during session creation
When a new session was being configured with invalid input data,
the error codes returned was not always consistent. Attempting
to start a session with a malformed capabilities configuration
will now return the invalid argument error consistently.
Assets
v0.25.0
Note to Windows users! With this release you must have the Microsoft Visual Studio redistributable runtime installed on your system for the binary to run. This is a known bug with this particular release that we intend to release a fix for soon.
Added
Added support for HTTP HEAD requests to the HTTPD
geckodriver now responds correctly to HTTP HEAD requests,
which can be used for probing whether it supports a particular API.
Thanks to Bastien Orivel for this patch.
Added support for searching for Nightly’s default path on macOS
If the location of the Firefox binary is not given, geckodriver
will from now also look for the location of Firefox Nightly in
the default locations. The ordered list of search paths on macOS
is as follows:
Thanks to Kriti Singh for this patch.
Support for application bundle paths on macOS
Thanks to Nupur Baghel for this patch.
macOS and Windows builds are signed
With this release of geckodriver, executables for macOS and Windows
are signed using the same certificate key as Firefox. This should
help in cases where geckodriver previously got misidentified as
a virus by antivirus software.
Removed
Dropped support for legacy Selenium web element references
The legacy way of serialising web elements, using <"ELEMENT": >,
has been removed in this release. This may break older Selenium
clients and clients which are otherwise not compatible with the
WebDriver standard.
Thanks to Shivam Singhal for this patch.
Changed
Refactored Marionette serialisation
Much of geckodriver’s internal plumbing for serialising WebDriver
requests to Marionette messages has been refactored to decrease
the amount of manual lifting.
This work should have no visible side-effects for users.
Thanks to Nupur Baghel for working on this throughout her
Outreachy internship at Mozilla.
Improved error messages for incorrect command-line usage
Fixed
Errors related to incorrect command-line usage no longer hidden
By mistake, earlier versions of geckodriver failed to print incorrect
flag use. With this release problems are again written to stderr.
Search system path for Firefox binary on BSDs
geckodriver would previously only search the system path for the
firefox binary on Linux. Now it supports different BSD flavours
as well.
Assets
v0.24.0
Added
Introduces strictFileInteractability capability
The new capabilitiy indicates if strict interactability checks
should be applied to elements. As strict
interactability checks are off by default, there is a change
in behaviour when using Element Send Keys
with hidden file upload controls.
Added new endpoint GET /session/
for taking full document screenshots, thanks to Greg Fraley.
Added new endpoint POST /session/
for the New Window command to create a new top-level browsing context,
which can be either a window or a tab. This feature requires
Firefox 66 or later.
geckodriver now sets the app.update.disabledForTesting preference
to prevent Firefox >= 65 from automatically updating whilst under
automation.
Removed
Changed
Allow file uploads to hidden elements
Through a series of changes to the WebDriver specification,
geckodriver is now aligned with chromedriver’s behaviour that
allows interaction with hidden elements.
This allows WebDriver to be used with various popular web
frameworks that—through indirection—hides the file upload control
and invokes it through other means.
Allow use of an indefinite script timeout for the Set Timeouts
command, thanks to reimu.
Fixed
Corrected Content-Type of response header to utf-8 to fix
an HTTP/1.1 compatibility bug.
Relaxed the deserialization of timeouts parameters to allow unknown
fields for the Set Timeouts command.
Fixed a regression in the Take Element Screenshot to not screenshot
the viewport, but the requested element.
Assets
v0.23.0
This release contains a number of fixes for regressions introduced
in 0.22.0, where we shipped a significant refactoring to the way
geckodriver internally dealt with JSON serialisation.
Removed
Changed
Fixed
desiredCapabilities and requiredCapabilities are again
recognised on session creation
Do however note that support for Selenium-styled new session
requests is temporary and that this will be removed sometime
before the 1.0 release.
duration field made optional on pause actions
A regression in 0.22.0 caused the pause action primitive to
require a duration field. This has now been fixed so that
pauses in action chains can be achieved with the default duration.
Log level formatted to expected Marionette input
A regression in 0.22.0 caused the log level to be improperly
formatted when using Firefox pre-releases. This is now fixed so
that the requested log level is correctly interpreted by Marionette.
temporary field on addon installation made optional
A regression in 0.22.0 caused the temporary field for POST
/session/
now been fixed so that an addon is installed permanently by default.
SHA1s in version information uses limited number of characters