Es posible que me confunda el cambio de Selenium a WebDriver y su respectiva documentación. En una sección sobre el diseño de prueba en la documentación, se habla de usar Assert vs Verify, como AssertElementPresent. Sin embargo, al seguir el tutorial de WebDriver y comenzar a configurar las pruebas, esto no parece estar disponible desde Python. ¿Estoy pasando por alto algo en la documentación, esto no es aplicable a WebDriver, no se aplica al uso de python, debería usar capacidades de python y no afirmar/verificar el comando de selenio, etc.?Assert/VerifyElementPresent with Python and WebDriver?
Respuesta
webdriver es una biblioteca para conducir buscadores. lo que quiere usar son los métodos * find_element * para localizar elementos y luego afirmar las condiciones en su contra.
por ejemplo, este código hace una afirmación sobre el contenido de un elemento:
from selenium import webdriver
browser = webdriver.Firefox()
browser.get('http://www.example.com')
element = browser.find_element_by_tag_name('h1')
assert element.text == 'Example Domains'
browser.quit()
- nota este ejemplo es Python puro, con una aserción desnudo. Es mejor usar un marco de prueba como unittest de python, que tiene aserciones más potentes.
En Selenium RC, existen métodos para verificar/afirmar. En WebDriver, no lo hacen. Además, es importante tener en cuenta lo que verifican y afirman hacen y su papel en sus pruebas. En Selenium RC, verificar se usa para realizar un control en la prueba, ya sea en texto, elementos o lo que sea. Assert, por otro lado, hará que una prueba falle y se detenga. Los beneficios y ventajas se discuten en el enlace al que hizo referencia.
WebDriver no tiene métodos de verificación/afirmación por decir. Las afirmaciones se realizan en la prueba en sí. Si echas un vistazo a la respuesta de Corey, realiza una "afirmación" en el texto de un elemento. Si el texto del elemento no es 'Dominios de ejemplo', se generará un AssertionError, fallando efectivamente su prueba. Pero, ¿qué pasa con una verificación? Bueno, como se mencionó, WebDriver no tiene uno. Pero aún podrías realizar algo equivalente haciendo una comparación.
if element.text != u'Example Domains':
print "Verify Failed: element text is not %r" % element.text
Entonces, en este caso, su prueba no fallará. Pero aún se realizará una verificación y se imprimirá en stdout.
Así que, al final, es una cuestión de lo que quiere fallar. Es más un diseño de prueba. Espero que esto ayude.
Verificar la aserción
driver= webdriver.Firefox()
String x =driver.findElement(By.xpath("//*[@id='userNavLabel']")).getText();
System.out.println(x);
//Assert.assertEquals(actual, expected)
Assert.assertEquals("Anandan Aranganath", x);
Pregunta de selenio python. No Java – bron
Se debe utilizar la siguiente función para comprobar que:
def is_element_present(self, how, what):
try: self.driver.find_element(by=how, value=what)
except NoSuchElementException as e: return False
return True
cual se genera por defecto cuando se exporta a Selenium IDE código Python.
A continuación, puede valer el elemento de la siguiente manera:
self.assertTrue(self.is_element_present(By.ID, "footer"))
self.assertTrue(self.is_element_present(By.CSS_SELECTOR, "header.global-header"))
Tenga en cuenta que se requiere la siguiente importación de usar By
:
from selenium.webdriver.common.by import By
Otra forma es la siguiente:
from selenium import webdriver
driver = webdriver.Firefox()
driver.get('http://www.testing.com')
element = driver.find_element_by_xpath('xpath of the element').text
assert element == 'Sample Text'
driver.quit()
- 1. Python Selenium WebDriver drag-and-drop
- 2. webdriver classname with space using java
- 3. Batch script with for loop and pipe
- 4. Seleccione Parent and Children With MySQL
- 5. nant logs with data and time stamp
- 6. C++ Qt Reflection with Copy and Assignment
- 7. Sql server DELETE and WITH cláusula
- 8. WPF Dynamic Layout with ItemsControl and Grid
- 9. Python Requests and Unicode
- 10. Crunching xml with python
- 11. ¿Webdriver admite pagefactory para Python?
- 12. selenio WebDriver ejemplo en Python
- 13. Cómo mouseOver en Python WebDriver
- 14. Python constructors and __init__
- 15. Python max and min
- 16. Python Decorators and inheritance
- 17. Python: ¿Socket and Threads?
- 18. Setup Factory Girl with Test :: Unit and Shoulda
- 19. Getting Rails 3 Generators with Rspec 2 and Mocha
- 20. Secure ASP.NET MVC application with SSL and client certificate authentication
- 21. XML Documentation Comments with Interfaces and implementation class (es)
- 22. Vim python support with non system python
- 23. Python Array Slice With Comma?
- 24. python problems with integer comparison
- 25. python Pool with worker Procesos
- 26. Python classes and __init__ method
- 27. Python regex search AND split
- 28. python nan and inf values
- 29. Maximice WebDriver (Selenium 2) en Python
- 30. Webdriver Screenshot
Debería ser una pregunta separada, pero es relevante aquí: ¿cómo puedo afirmar que un n elemento no está presente en la página? – Priednis
Encontré mi respuesta aquí: http://sqa.stackexchange.com/questions/3481/quicker-way-to-assert-that-an-element-does-not-exist?rq=1 – Priednis
Prefiero intentarlo/excepto el bloque NoSuchElementException para la llamada find_element_by_tag_name, ya que si el elemento no se encuentra, entonces la prueba marcará una excepción ERROR en lugar de una falla ... ¿O hay una manera de afirmar que el elemento está presente sin este inconveniente? –