2011-05-31 17 views
74

Estoy en la instancia EC2. Entonces no hay GUI.¿Cómo ejecuto Selenium en Xvfb?

$pip install selenium 
$sudo apt-get install firefox xvfb 

Entonces hago esto:

$Xvfb :1 -screen 0 1024x768x24 2>&1 >/dev/null & 

$DISPLAY=:1 java -jar selenium-server-standalone-2.0b3.jar 
05:08:31.227 INFO - Java: Sun Microsystems Inc. 19.0-b09 
05:08:31.229 INFO - OS: Linux 2.6.32-305-ec2 i386 
05:08:31.233 INFO - v2.0 [b3], with Core v2.0 [b3] 
05:08:32.121 INFO - RemoteWebDriver instances should connect to: http://127.0.0.1:4444/wd/hub 
05:08:32.122 INFO - Version Jetty/5.1.x 
05:08:32.123 INFO - Started HttpContext[/selenium-server/driver,/selenium-server/driver] 
05:08:32.124 INFO - Started HttpContext[/selenium-server,/selenium-server] 
05:08:32.124 INFO - Started HttpContext[/,/] 
05:08:32.291 INFO - Started [email protected] 
05:08:32.292 INFO - Started HttpContext[/wd,/wd] 
05:08:32.295 INFO - Started SocketListener on 0.0.0.0:4444 
05:08:32.295 INFO - Started [email protected] 

Grande, todo debería funcionar ahora, ¿verdad?

Cuando ejecuto mi código:

from selenium import webdriver 
from selenium.common.exceptions import NoSuchElementException 
from selenium.webdriver.common.keys import Keys 

browser = webdriver.Firefox() 
browser.get("http://www.yahoo.com") 

me sale esto:

Error: cannot open display: :0 
+2

Si está en un sistema sin X funcionando, mostrar: 0 debería estar disponible. Intente ejecutar Xvfb: 0 - también vea xvfb-run como lo menciona @ema – fijiaaron

+0

Para futuros seguidores, describí mi solución para Ubuntu Server: https://www.namekdev.net/2016/08/selenium-server-without- x-window-system-xvfb/ – Namek

Respuesta

30

abrir un terminal y ejecuta este comando xhost +. Estos comandos deben ejecutarse cada vez que reinicie su máquina. Si todo funciona bien puede ser usted puede agregar esto a comandos de inicio

Asegúrese también en su archivo/etc/environment hay una línea

export DISPLAY=:0.0 

Y luego, ejecutar las pruebas para ver si el problema es resuelto.

Todos, tenga en cuenta el comentario de sardathrion a continuación antes de usar esto.

+0

Solo necesita ejecutar java -jar selenium-server-standalone-2.0b3.jar desde la línea de comandos y luego ejecutar sus pruebas –

+0

Estoy en una instancia de EC2, por lo que no hay GUI. xhost: no se puede abrir la pantalla ": 0.0" – TIMEX

+0

@owa También necesita la variable de entorno DISPLAY en el entorno del cliente. – Keith

20

Esta es la configuración que utilizo:

Antes de ejecutar las pruebas, ejecute:

export DISPLAY=:99 
/etc/init.d/xvfb start 

Y después de las pruebas:

/etc/init.d/xvfb stop

El archivo init.d yo uso es el siguiente:

#!/bin/bash 

XVFB=/usr/bin/Xvfb 
XVFBARGS="$DISPLAY -ac -screen 0 1024x768x16" 
PIDFILE=${HOME}/xvfb_${DISPLAY:1}.pid 
case "$1" in 
    start) 
    echo -n "Starting virtual X frame buffer: Xvfb" 
    /sbin/start-stop-daemon --start --quiet --pidfile $PIDFILE --make-pidfile --background --exec $XVFB -- $XVFBARGS 
    echo "." 
    ;; 
    stop) 
    echo -n "Stopping virtual X frame buffer: Xvfb" 
    /sbin/start-stop-daemon --stop --quiet --pidfile $PIDFILE 
    echo "." 
    ;; 
    restart) 
    $0 stop 
    $0 start 
    ;; 
    *) 
    echo "Usage: /etc/init.d/xvfb {start|stop|restart}" 
    exit 1 
esac 
exit 0
+0

Hice exactamente esto y luego ejecuté mi script. Sin embargo, sigo teniendo esto: Error: no se puede abrir la pantalla:: 0. Además, ¿necesito ejecutar el servidor de selenio java? Parece que no importa si lo ejecuto o no ... – TIMEX

+2

owalla, si usa WebDriver, entonces no necesita el Servidor Selenium Java. –

146

Puede usar PyVirtualDisplay (un contenedor de Python para Xvfb) para ejecutar pruebas de WebDriver sin cabeza.

#!/usr/bin/env python 

from pyvirtualdisplay import Display 
from selenium import webdriver 

display = Display(visible=0, size=(800, 600)) 
display.start() 

# now Firefox will run in a virtual display. 
# you will not see the browser. 
browser = webdriver.Firefox() 
browser.get('http://www.google.com') 
print browser.title 
browser.quit() 

display.stop() 

more info


También puede utilizar xvfbwrapper, que es un módulo similar (pero no tiene dependencias externas):

from xvfbwrapper import Xvfb 

vdisplay = Xvfb() 
vdisplay.start() 

# launch stuff inside virtual display here 

vdisplay.stop() 

o mejor aún, lo utilizan como un contexto gerente:

from xvfbwrapper import Xvfb 

with Xvfb() as xvfb: 
    # launch stuff inside virtual display here. 
    # It starts/stops in this code block. 
+4

esto mostró el navegador en OSX 10.7.4 – Andrei

+2

@Andrei OSX no usa X11 de forma predeterminada –

+0

Utilizé esta respuesta para que funcione con vagrant + PyCharm + Django en OS X: http://stackoverflow.com/q/ 29343109 – chachan

42

La forma más sencilla es probablemente usar XVFB plazo:

DISPLAY=:1 xvfb-run java -jar selenium-server-standalone-2.0b3.jar 

XVFB plazo no toda la autoridad X de baile para usted, darle una oportunidad!

+0

Esto es justo lo que estaba buscando. Comenzar Xvfb por sí mismo no parecía funcionar para mí, pero usar xvfb-run fue suficiente. Gracias. –

+8

El '' DISPLAY =: 1'' no es necesario; xvfb-run establece la variable de entorno DISPLAY en otra cosa (generalmente '': 99'') antes de iniciar el comando especificado (en su caso, '' java -jar selenium-server ... '') –

3

Si usa Maven, puede usar xvfb-maven-plugin para iniciar xvfb antes de las pruebas, ejecútelas utilizando la variable de entorno relacionada DISPLAY, y detenga xvfb después de todo.

0

En mi caso en CentOS 7:

paquetes:

PIP_PACKAGES="selenium pyvirtualdisplay" 
YUM_PACKAGES="python34-pip httpd firefox xorg-x11-server-Xvfb expect python34-paramiko" 

pantalla:

su --command="Xvfb :22 -screen 0 1024x768x16 > /dev/null 2>&1 &" root 
export DISPLAY=:22 

prueba sencilla:

#!/usr/bin/env python3 

from selenium import webdriver 
from pyvirtualdisplay import Display 

browser = webdriver.Firefox() 
browser.get('https://google.com') 
if "Google" in browser.title: 
    print(browser.title) 
Cuestiones relacionadas