Selenium usando Python-El ejecutable Geckodriver debe estar en la RUTA


Soy nuevo en la programación y empecé con Python hace unos 2 meses y estoy repasando el de Sweigart Automatice las cosas aburridas con texto Python. Estoy usando IDLE y ya tengo instalado el módulo selenium y el navegador Firefox. Cada vez que intenté ejecutar la función webdriver, obtengo esto:

from selenium import webdriver
browser = webdriver.Firefox()

Excepción: -

Exception ignored in: <bound method Service.__del__ of <selenium.webdriver.firefox.service.Service object at 0x00000249C0DA1080>>
Traceback (most recent call last):
  File "C:\Python\Python35\lib\site-packages\selenium\webdriver\common\service.py", line 163, in __del__
    self.stop()
  File "C:\Python\Python35\lib\site-packages\selenium\webdriver\common\service.py", line 135, in stop
    if self.process is None:
AttributeError: 'Service' object has no attribute 'process'
Exception ignored in: <bound method Service.__del__ of <selenium.webdriver.firefox.service.Service object at 0x00000249C0E08128>>
Traceback (most recent call last):
  File "C:\Python\Python35\lib\site-packages\selenium\webdriver\common\service.py", line 163, in __del__
    self.stop()
  File "C:\Python\Python35\lib\site-packages\selenium\webdriver\common\service.py", line 135, in stop
    if self.process is None:
AttributeError: 'Service' object has no attribute 'process'
Traceback (most recent call last):
  File "C:\Python\Python35\lib\site-packages\selenium\webdriver\common\service.py", line 64, in start
    stdout=self.log_file, stderr=self.log_file)
  File "C:\Python\Python35\lib\subprocess.py", line 947, in __init__
    restore_signals, start_new_session)
  File "C:\Python\Python35\lib\subprocess.py", line 1224, in _execute_child
    startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    browser = webdriver.Firefox()
  File "C:\Python\Python35\lib\site-packages\selenium\webdriver\firefox\webdriver.py", line 135, in __init__
    self.service.start()
  File "C:\Python\Python35\lib\site-packages\selenium\webdriver\common\service.py", line 71, in start
    os.path.basename(self.path), self.start_error_message)
selenium.common.exceptions.WebDriverException: Message: 'geckodriver' executable needs to be in PATH. 

Creo que necesito establecer el camino para geckodriver pero no estoy seguro de cómo, así que ¿puede alguien decirme cómo haría esto?

Author: Paolo Forgia, 2016-10-24

18 answers

Selenio.común.salvedad.WebDriverException: Mensaje: el ejecutable 'geckodriver' necesita estar en PATH.

En primer lugar, tendrá que descargar el último ejecutable geckodriver desde aquí para ejecutar el último firefox usando selenium

En realidad, los enlaces del cliente Selenium intentan localizar el ejecutable geckodriver desde el sistema PATH. Necesitará agregar el directorio que contiene el ejecutable a la ruta del sistema.

  • En sistemas Unix usted puede hacer lo siguiente para añadirlo a la ruta de búsqueda de su sistema, si está utilizando un shell compatible con bash:

    export PATH=$PATH:/path/to/directory/of/executable/downloaded/in/previous/step
    
  • En Windows tendrá que actualizar la variable del sistema Path para agregar la ruta completa del directorio al ejecutable geckodriver manualmente o línea de comandos(no olvide reiniciar su sistema después de agregar el ejecutable geckodriver en la RUTA del sistema para que surta efecto) . El principio es el mismo que en Unix.

Ahora puedes ejecutar tu código igual que lo estás haciendo de la siguiente manera: -

from selenium import webdriver

browser = webdriver.Firefox()

Selenio.común.salvedad.WebDriverException: Mensaje: Ubicación binaria esperada del navegador, pero no se puede encontrar el binario en la ubicación predeterminada, no ' moz: firefoxOptions.binario ' capacidad proporcionada, y ningún indicador binario establecido en la línea de comandos

Excepción claramente indica que ha instalado firefox alguna otra ubicación mientras Selenium está tratando de encontrar firefox y lanzar desde el valor predeterminado ubicación, pero no pudo encontrar. Es necesario proporcionar explícitamente firefox instalado ubicación binaria para lanzar firefox como a continuación: -

from selenium import webdriver
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary

binary = FirefoxBinary('path/to/installed firefox binary')
browser = webdriver.Firefox(firefox_binary=binary)
 234
Author: Saurabh Gaur,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-24 03:12:12

Este paso SE RESOLVIÓ para mí en ubuntu firefox 50.

  1. Descargar geckodriver

  2. Copiar geckodriver en / usr / local / bin

NO es necesario añadir

firefox_capabilities = DesiredCapabilities.FIREFOX
firefox_capabilities['marionette'] = True
firefox_capabilities['binary'] = '/usr/bin/firefox'
browser = webdriver.Firefox(capabilities=firefox_capabilities)
 80
Author: Andrea Perdicchia,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-10 17:29:03

Esto lo resolvió para mí.

from selenium import webdriver
driver = webdriver.Firefox(executable_path=r'your\path\geckodriver.exe')
driver.get('http://inventwithpython.com')
 79
Author: Nesa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-08 19:45:54

La respuesta de @saurabh resuelve el problema, pero no explica por qué Automatizar las cosas Aburridas con Python no incluye esos pasos.

Esto se debe a que el libro está basado en selenio 2.x y el controlador de Firefox para esa serie no necesita el controlador gecko. La interfaz de Gecko para manejar el navegador no estaba disponible cuando selenium estaba siendo desarrollado.

La última versión en el selenio 2.la serie x es 2.53.6 (ver por ejemplo esto responde , para una vista más fácil de las versiones).

La página de la versión 2.53.6 no menciona al gecko en absoluto. Pero desde la versión 3.0.2 la documentación indica explícitamente que necesita instalar el controlador gecko.

Si después de una actualización (o instalación en un nuevo sistema), su software que funcionaba bien antes (o en su sistema antiguo) ya no funciona y tiene prisa, pin la versión selenium en su virtualenv haciendo

pip install selenium==2.53.6

Pero, por supuesto, la solución a largo plazo para el desarrollo consiste en configurar un nuevo virtualenv con la última versión de selenium, instalar el controlador gecko y probar si todo sigue funcionando como se esperaba. Pero la versión principal puede introducir otros cambios en la API que no están cubiertos por su libro, por lo que es posible que desee seguir con el selenium más antiguo, hasta que esté lo suficientemente seguro de que puede solucionar cualquier discrepancia entre la API selenium2 y selenium3 usted mismo.

 21
Author: Anthon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:18:27

En macOS con Homebrew ya instalado, simplemente puede ejecutar el comando de Terminal

$ brew install geckodriver

Debido a que homebrew ya extendió el PATH no hay necesidad de modificar ningún script de inicio.

 12
Author: roskakori,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-03 14:09:56

Para configurar geckodriver para Selenium Python:

Necesita establecer la ruta geckodriver con FirefoxDriver como se muestra a continuación:

self.driver = webdriver.Firefox(executable_path = 'D:\Selenium_RiponAlWasim\geckodriver-v0.18.0-win64\geckodriver.exe')

Descargue geckodriver para su sistema operativo adecuado (desde https://github.com/mozilla/geckodriver/releases ) - > Extraerlo en una carpeta de su elección - > Establecer la ruta correctamente como se mencionó anteriormente

Estoy usando Python 3.6.2 y Selenium WebDriver 3.4.3 en Windows 10.

Otra forma de configurar geckodriver:

I) Simplemente pegue el geckodriver.exe bajo / Python / Scripts / (En mi caso la carpeta era: C:\Python36\Scripts)
ii) Ahora escriba el código simple de la siguiente manera:

self.driver = webdriver.Firefox()
 9
Author: Ripon Al Wasim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-26 11:33:48

Pasos para MAC:

La solución simple es descargar GeckoDriver y agregarlo a la RUTA de su sistema. Puede utilizar cualquiera de los dos enfoques:

Método corto:

1) Descarga y descomprime Geckodriver.

2) Mencione la ruta al iniciar el controlador:

driver = webdriver.Firefox(executable_path='/your/path/to/geckodriver')

Método largo:

1) Descarga y descomprime Geckodriver.

2) Abrir .bash_profile. Si aún no lo ha creado, puede hacerlo usando el comando: touch ~/.bash_profile. Luego ábrelo usando: open ~/.bash_profile

3) Teniendo en cuenta que el archivo GeckoDriver está presente en su carpeta de descargas, puede agregar las siguientes líneas al archivo .bash_profile:

PATH="/Users/<your-name>/Downloads/geckodriver:$PATH"
export PATH

De esta manera, está anexando la ruta de acceso a GeckoDriver a la RUTA de su sistema. Esto le indica al sistema dónde se encuentra GeckoDriver al ejecutar los scripts de Selenium.

4) Guarde el .bash_profile y fuerce su ejecución. Esto carga los valores inmediatamente sin tener que reiniciar. Para hacer esto, puede ejecutar lo siguiente orden:

source ~/.bash_profile

5) Eso es todo. ¡Has TERMINADO!. Ahora puede ejecutar el script Python.

 5
Author: Umang Sardesai,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-18 09:52:51

En realidad he descubierto que se puede utilizar el último geckodriver sin ponerlo en la ruta del sistema. Actualmente estoy usando

Https://github.com/mozilla/geckodriver/releases/download/v0.12.0/geckodriver-v0.12.0-win64.zip

Firefox 50.1.0

Python 3.5.2

Selenio 3.0.2

Windows 10

Estoy ejecutando un VirtualEnv (que administro usando PyCharm, supongo que usa Pip para instalar todo)

En el siguiente código puedo usar un ruta específica para el geckodriver usando el parámetro executable_path (Descubro esto echando un vistazo en Lib\site-packages\selenium\webdriver\firefox\webdriver.py ). Tenga en cuenta que tengo la sospecha de que el orden de los argumentos de los parámetros al llamar al webdriver es importante, por lo que el executable_path es el último en mi código (2nd last line off to the far right)

También puede notar que uso un perfil personalizado de Firefox para evitar el problema sec_error_unknown_issuer con el que se encontrará si el sitio que está probando tiene un certificado que no es de confianza. ver ¿Cómo deshabilitar la advertencia de conexión no confiable de Firefox usando Selenium?

Después de la investigación se encontró que el controlador de Marionetas está incompleto y todavía en progreso, y ninguna cantidad de configuración de varias capacidades u opciones de perfil para descartar o establecer certificados iba a funcionar. Así que era más fácil usar un perfil personalizado.

De todos modos aquí está el código de cómo conseguí que el geckodriver funcione sin estar en el camino:

from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

firefox_capabilities = DesiredCapabilities.FIREFOX
firefox_capabilities['marionette'] = True

#you probably don't need the next 3 lines they don't seem to work anyway
firefox_capabilities['handleAlerts'] = True
firefox_capabilities['acceptSslCerts'] = True
firefox_capabilities['acceptInsecureCerts'] = True

#In the next line I'm using a specific FireFox profile because
# I wanted to get around the sec_error_unknown_issuer problems with the new Firefox and Marionette driver
# I create a FireFox profile where I had already made an exception for the site I'm testing
# see https://support.mozilla.org/en-US/kb/profile-manager-create-and-remove-firefox-profiles#w_starting-the-profile-manager

ffProfilePath = 'D:\Work\PyTestFramework\FirefoxSeleniumProfile'
profile = webdriver.FirefoxProfile(profile_directory=ffProfilePath)
geckoPath = 'D:\Work\PyTestFramework\geckodriver.exe'
browser = webdriver.Firefox(firefox_profile=profile, capabilities=firefox_capabilities, executable_path=geckoPath)
browser.get('http://stackoverflow.com')
 3
Author: Roochiedoor,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:02:57

Estoy usando Windows 10 y esto funcionó para mí:

  1. Descarga geckodriver desde aquí. Descargue la versión correcta para el equipo que está utilizando
  2. Descomprima el archivo que acaba de descargar y corte/copie el ".archivo exe" que contiene
  3. Vaya a C:{su carpeta raíz de python}. El mío era C:\Python27. Pega el geckodriver.archivo exe en esta carpeta.
  4. Reinicie su entorno de desarrollo.
  5. Intente ejecutar el código de nuevo, debería funcionar ahora.
 3
Author: anotherNoob,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-19 14:43:10

Algunas entradas/aclaraciones adicionales para futuros lectores de este hilo:

Lo siguiente es suficiente como resolución para Windows 7, Python 3.6, selenium 3.11:

La nota de@dsalaj en este hilo anterior para Unix también es aplicable a Windows; jugueteando con la ruta env. variable en el nivel de Windows y el reinicio del sistema de Windows se puede evitar.

(1) Descargue geckodriver (como se describe en este hilo anterior) y coloque el geckdriver (descomprimido).exe at X:\Folder\of\your\choice

(2) Ejemplo de código Python:

import os;
os.environ["PATH"] += os.pathsep + r'X:\Folder\of\your\choice';

from selenium import webdriver;
browser = webdriver.Firefox();
browser.get('http://localhost:8000')
assert 'Django' in browser.title

Notas: (1) El código anterior puede tardar unos 10 segundos en abrir el navegador Firefox para la url especificada.
(2) La consola de python mostrará el siguiente error si no hay ningún servidor que ya se esté ejecutando en la url especificada o sirviendo una página con el título que contiene la cadena 'Django': selenio.común.salvedad.WebDriverException: Mensaje: Página de error alcanzada: acerca de: neterror?e = connectionFailure & u = http % 3A / / localhost%3A8000 / &c=UTF-8&f=regular & d=Firefox%20can%E2%80% 9

 3
Author: Snidhi Sofpro,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-16 07:14:54

Si está utilizando Anaconda , todo lo que tiene que hacer es activar su entorno virtual y luego instalar geckodriver usando el siguiente comando :

    conda install -c conda-forge geckodriver
 3
Author: Rodolfo Alvarez,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-26 10:12:45

Es realmente bastante triste que ninguno de los libros publicados en Selenium / Python y la mayoría de los comentarios sobre este tema a través de Google no explican claramente la lógica de ruta para configurar esto en Mac (todo es Windows!!!!). Los youtubes todo recogida en el "después" tienes la configuración pathing (en mi mente, la salida barata!). Por lo tanto, para ustedes maravillosos usuarios de Mac, use lo siguiente para editar sus archivos de ruta de bash:

>$toque ~/.bash_profile; abrir ~/.bash_profile

A continuación, añadir un path algo así.... * # Establecer RUTA de acceso para geckodriver PATH= " / usr / bin / geckodriver: {{PATH}" ruta DE exportación

Establecer la ruta de acceso para Selenium firefox

PATH="~/Users/yourNamePATH/VEnvPythonInterpreter/lib/python2.7/site-packages/selenium/webdriver/firefox/:${PATH}" ruta DE exportación

Establecer la ruta para el ejecutable en el controlador de firefox

PATH="/Users/yournamePATH/VEnvPythonInterpreter/lib/python2.7/site-packages/selenium/webdriver/common/service.py:${PATH}" exportación RUTA *

Esto funcionó para mí. Mi preocupación es cuándo comenzará la comunidad de Selenium Windows a jugar el juego real e incluirnos a los usuarios de Mac en su membresía arrogante del club.

 2
Author: JustASteve,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-19 21:38:27

La forma más fácil para Windows!
Acabo de descargar la última versión geckodriver (tengo win10) de aquí y agregó que geckodriver.exe archivo en el directorio python C:\Users\my.name (que ya está en la ruta) ¡Funcionó para mí!

 2
Author: Jalles10,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-22 23:16:17

Selenio responde a esta pregunta en su DESCRIPCIÓN.rst

Drivers
=======

Selenium requires a driver to interface with the chosen browser. Firefox,
for example, requires `geckodriver <https://github.com/mozilla/geckodriver/releases>`_, 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.

Básicamente solo tienes que descargar el geckodriver, descomprimirlo y mover el ejecutable a tu carpeta /usr/bin

 1
Author: Peter Graham,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-19 15:21:55

Mac 10.12.1 python 2.7.10 este trabajo para mí :)

def download(url):
firefox_capabilities = DesiredCapabilities.FIREFOX
firefox_capabilities['marionette'] = True
browser = webdriver.Firefox(capabilities=firefox_capabilities,
                            executable_path=r'/Users/Do01/Documents/crawler-env/geckodriver')
browser.get(url)
return browser.page_source
 0
Author: do01,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-15 21:59:47

En Raspberry Pi tuve que crear desde ARM driver y establecer el geckodriver y la ruta de registro en:

Sudo nano /usr/local/lib/python2.7/dist-packages/selenium/webdriver/firefox/webdriver.py

def __init__(self, firefox_profile=None, firefox_binary=None,
             timeout=30, capabilities=None, proxy=None,
             executable_path="/PATH/gecko/geckodriver",                     
firefox_options=None,
             log_path="/PATH/geckodriver.log"):
 0
Author: Nathan Gisvold,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-27 20:10:46

Visite Gecko Driver obtenga la url del controlador gecko en la sección de descargas.

Clonar este repositorio https://github.com/jackton1/script_install.git

cd script_install

Ejecutar

./installer --gecko-driver url_to_gecko_driver

 0
Author: jackotonye,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-17 16:02:45

Estoy usando Windows 10 y Anaconda2. Intenté establecer la variable de ruta del sistema, pero no funcionó. Luego simplemente agregué geckodriver.archivo exe a la carpeta Anaconda2/Scripts y todo funciona muy bien ahora. Para mí el camino era:-

C:\Users\Bhavya\Anaconda2\Scripts

 0
Author: Bhavya Ghai,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-13 01:48:04