2011-10-09 31 views

Respuesta

14

normalmente hago algo a lo largo de las líneas de:

assertEquals(driver.getPageSource().contains("sometext"), true); 

assertTrue(driver.getPageSource().contains("sometext")); 
+0

Esto es bueno Soltion, pero parece que no es el equivalente exacto - mira a los comentarios aquí: http: // rostislav- matl.blogspot.com/2011/03/moving-to-selenium-2-on-webdriver-part.html –

3

Sé que esto es un poco viejo, pero me pareció una buena respuesta aquí: Selenium 2.0 Web Driver: implementation of isTextPresent

En Python, esto se parece a:

def is_text_present(self, text): 
    try: el = self.driver.find_element_by_tag_name("body") 
    except NoSuchElementException, e: return False 
    return text in el.text 
3

O si desea comprobar realmente el contenido de texto de un WebElement que podría hacer algo como:

assertEquals(getMyWebElement().getText(), "Expected text"); 
6

La fuente de la página contiene etiquetas HTML que pueden romper el texto de búsqueda y dar como resultado negativos falsos. Encontré que esta solución funciona de manera similar a la API isTextPresent de Selenium RC.

WebDriver driver = new FirefoxDriver(); //or some other driver 
driver.findElement(By.tagName("body")).getText().contains("Some text to search") 

haciendo getText y luego contiene tiene un compromiso de rendimiento. Es posible que desee restringir el árbol de búsqueda utilizando un WebElement más específico.

2

Código de Java Selenium2 para isTextPresent (Selenio Código IDE) en junit4

public boolean isTextPresent(String str) 
{ 
    WebElement bodyElement = driver.findElement(By.tagName("body")); 
    return bodyElement.getText().contains(str); 
} 

@Test 
public void testText() throws Exception { 
    assertTrue(isTextPresent("Some Text to search")); 
} 
1

He escrito el siguiente método:

public boolean isTextPresent(String text){ 
     try{ 
      boolean b = driver.getPageSource().contains(text); 
      return b; 
     } 
     catch(Exception e){ 
      return false; 
     } 
    } 

El método anterior se denomina de la siguiente manera:

assertTrue(isTextPresent("some text")); 

Está funcionando muy bien.

+0

assertTrue (boolean) y otros métodos assert son de JUnit. Supongo que no están con los paquetes java predeterminados. – MKod

+0

¿No cree que habrá un problema de rendimiento con "driver.getPageSource(). Contains (text)". Creo que buscará mucho texto de la fuente de la página. Si esa es la única forma de encontrar un texto en particular, ¿cómo justificas el tiempo transcurrido y el rendimiento del código? Gracias por publicar una buena pregunta. – MKod

+0

@MKod: estoy de acuerdo contigo. Puede causar problemas de rendimiento ya que busca texto completo de una página. Necesita descubrir una forma (s) alternativa. Supongo que WebDriver mejoraría día a día –

0

Prueba si el texto está presente en Ruby (un enfoque para principiantes) usando firefox como navegador de destino.

1) Debe, por supuesto, para descargar y ejecutar el archivo jar servidor de selenio con algo como:

java - jar C:\Users\wmj\Downloads\selenium-server-standalone-2.25.0.jar 

2) Es necesario instalar el rubí, y en su carpeta bin, las órdenes de marcha para instalar gemas adicionales:

gem install selenium-webdriver 
gem install test-unit 

3) crear un banco de pruebas it.rb archivo que contiene:

require "selenium-webdriver" 
require "test/unit" 

class TestIt < Test::Unit::TestCase 

    def setup 
     @driver = Selenium::WebDriver.for :firefox 
     @base_url = "http://www.yoursitehere.com" 
     @driver.manage.timeouts.implicit_wait = 30 
     @verification_errors = [] 
     @wait = Selenium::WebDriver::Wait.new :timeout => 10 
    end 


    def teardown 
     @driver.quit 
     assert_equal [], @verification_errors 
    end 

    def element_present?(how, what) 
     @driver.find_element(how, what) 
     true 
     rescue Selenium::WebDriver::Error::NoSuchElementError 
     false 
    end 

    def verify(&blk) 
     yield 
     rescue Test::Unit::AssertionFailedError => ex 
     @verification_errors << ex 
    end 

    def test_simple 

     @driver.get(@base_url + "/") 
     # simulate a click on a span that is contained in a "a href" link 
     @driver.find_element(:css, "#linkLogin > span").click 
     # we clear username textbox 
     @driver.find_element(:id, "UserName").clear 
     # we enter username 
     @driver.find_element(:id, "UserName").send_keys "bozo" 
     # we clear password 
     @driver.find_element(:id, "Password").clear 
     # we enter password 
     @driver.find_element(:id, "Password").send_keys "123456" 
     # we click on a button where its css is named as "btn" 
     @driver.find_element(:css, "input.btn").click 

     # you can wait for page to load, to check if text "My account" is present in body tag 
     assert_nothing_raised do 
      @wait.until { @driver.find_element(:tag_name=>"body").text.include? "My account" } 
     end 
     # or you can use direct assertion to check if text "My account" is present in body tag 
     assert(@driver.find_element(:tag_name => "body").text.include?("My account"),"My account text check!") 

     @driver.find_element(:css, "input.btn").click 
    end 
end 

4) rubí ejecutar:

ruby test-it.rb 
2

el siguiente código usando Java en WebDriver debería funcionar:

assertTrue(driver.getPageSource().contains("Welcome Ripon Al Wasim")); 
assertTrue(driver.findElement(By.id("widget_205_after_login")).getText().matches("^[\\s\\S]*Welcome ripon[\\s\\S]*$"));