Buscar..


Observaciones

Selenium es una poderosa biblioteca de comandos en múltiples idiomas (C #, Haskell, Java, JavaScript, Objective-C, Perl, PHP, Python, R y Ruby) que le permiten al programador automatizar la interacción del navegador. Esto es increíblemente útil para los desarrolladores que prueban aplicaciones.

El selenio ofrece métodos para:

  • Encuentra un elemento en una página web
  • Haga clic en un elemento
  • Enviar una cadena a un elemento
  • Navegar a una página web
  • Cambiar a una pestaña diferente en la misma ventana del navegador
  • Toma una captura de pantalla de una página web

Usando estos métodos, un desarrollador puede tener pruebas automáticas de verificación:

  • Si un elemento está en una página y es visible para un usuario
  • Un formulario de búsqueda o login
  • Botones o elementos interactivos
  • Verificar los valores o atributos de un elemento.

Selenium se ejecuta en webdrivers, que son similares a un navegador web normal pero permiten que Selenium interactúe con ellos. Una prueba de Selenium normalmente abre una nueva instancia de controlador de cualquier navegador que el desarrollador esté probando, lo que siempre es una pizarra limpia. De esta manera, cuando se ejecuta una prueba de Selenium, el desarrollador no tiene que preocuparse por las cookies anteriores, o por un caché del navegador que afecte los resultados de su aplicación.

Selenium también funciona cuando se ejecuta un controlador web en modo sin cabeza.

Versiones

Versión Fecha de lanzamiento
3.4.0 2017-04-11
3.3 2017-04-07
3.2 2017-02-27
3.1 2017-02-13
3.0.1 2016-11-19
3.0 2016-10-11

Prueba simple de selenio en Java

El código de abajo es un simple programa java que usa selenio. El viaje del siguiente código es

  1. Abre el navegador Firefox
  2. Abrir google page
  3. Imprimir el título de la página de Google
  4. Encuentra la ubicación del cuadro de búsqueda
  5. Pase el valor como Selenium en el cuadro de búsqueda
  6. Enviar el formulario
  7. Apagar el navegador
package org.openqa.selenium.example;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;

public class Selenium2Example  {
    public static void main(String[] args) {
        // Create a new instance of the Firefox driver
        WebDriver driver = new FirefoxDriver();

        // An implicit wait is to tell WebDriver to poll the DOM for a certain amount of time 
        // when trying to find an element or elements if they are not immediately available. 
        // The default setting is 0. Once set, the implicit wait is set for the life of the WebDriver object instance.   
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

        // Maximize the browser window to fit into screen
        driver.manage().window().maximize();
        
        // Visit Google
        driver.get("http://www.google.com");

        // Check the title of the page
        System.out.println("Page title is: " + driver.getTitle());

        // Find the text input element by its name
        WebElement element = driver.findElement(By.name("q"));

        // Enter something to search for
        element.sendKeys("Selenium!");

        // Now submit the form. WebDriver will find the form for us from the element
        element.submit();

        //Close the browser
        driver.quit();
    }
}

Test simple de selenio en pitón.

from selenium import webdriver

# Create a new chromedriver
driver = webdriver.Chrome()

# Go to www.google.com
driver.get("https://www.google.com")

# Get the webelement of the text input box
search_box = driver.find_element_by_name("q")

# Send the string "Selenium!" to the input box
seach_box.send_keys("Selenium!")

# Submit the input, which starts a search
search_box.submit()

# Wait to see the results of the search
time.sleep(5)

# Close the driver
driver.quit()

Configuración de python Selenium a través de terminal (BASH)

La forma más fácil es usar pip y VirtualEnv . El selenio también requiere python 3. * .

Instale virtualenv usando:

$: pip install virtualenv

Cree / ingrese un directorio para sus archivos de Selenium:

$: cd my_selenium_project

Cree un nuevo VirtualEnv en el directorio para sus archivos de Selenium:

$: virtualenv -p /usr/bin/python3.0 venv

Activar el VirtualEnv:

$: source venv/bin/active

Debería ver ahora ver (venv) al comienzo de cada línea de bash. Instala Selenium usando pip:

$: pip install selenium

Selenium viene con el controlador FireFox por defecto.
Si desea ejecutar Selenium en google chrome, también haga esto:

$: pip install chromedriver

Ahora tienes un VirtualEnv controlado por versión. Para asegurarse de que todo está configurado correctamente:

Iniciar python:

$: python

Imprime:

Python 2.7.10 (default, Jul 14 2015, 19:46:27) 
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

Cree un nuevo controlador web (en este caso, un chromedriver), y vaya a www.google.com:

>>> from selenium import webdriver
>>> driver = webdriver.Chrome()
>>> driver.get("https://www.google.com")

Cierre el controlador y el intérprete de python:

>>> driver.quit()
>>> quit()

Desactivar el VirtualEnv:

$: deactivate

Si el driver = webdriver.Chrome() línea driver = webdriver.Chrome() está arrojando errores:

  • Asegúrate de que también tienes instalado el navegador chrome. Si no lo hace, el chromedriver de Selenium no puede acceder al binario de Chrome.
  • webdriver.Chrome () también puede tomar un parámetro para la ubicación de su chromedriver. Si lo instaló utilizando pip, pruebe (en mac) driver = webdriver.Chrome("./venv/selenium/webdriver/chromedriver") .

Ejemplo simple de selenio en C #

//Create a new ChromeDriver
IWebDriver driver = new ChromeDriver();

//Navigate to www.google.com
driver.Navigate().GoToUrl("https://www.google.com");

//Find the WebElement of the search bar
IWebElement element = driver.FindElement(By.Name("q"));

//Type Hello World into search bar
element.SendKeys("Hello World");

//Submit the input
element.Submit();

//Close the browser
driver.Quit();


Modified text is an extract of the original Stack Overflow Documentation
Licenciado bajo CC BY-SA 3.0
No afiliado a Stack Overflow