Assert/verifyelementpresent With Python And Webdriver?
Solution 1:
webdriver is a library for driving browsers. what you want to use are the *find_element* methods to locate elements and then assert conditions against them.
for example, this code does an assertion on content of an element:
from selenium importwebdriverbrowser= webdriver.Firefox()
browser.get('http://www.example.com')
element = browser.find_element_by_tag_name('h1')
assert element.text == 'Example Domains'
browser.quit()
- note this example is pure python with a bare assert. It is better to use a test framework like python's unittest, which has more powerful assertions.
Solution 2:
In Selenium RC, verify/assert methods exist. In WebDriver, they don't. Also, its important to note what verify and assert does and their role in your tests. In Selenium RC, verify is used to perform a check in your test, whether it may be on text, elements, or what have you. Assert, on the other hand, will cause a test to fail and stop. The benefits and advantages are discussed in the link you referenced.
WebDriver doesn't have verify/assert methods per say. Assertions are performed in the test itself. If you take a look at Corey's answer, he performs an "assert" on an element's text. If the element's text is not 'Example Domains' an AssertionError will be raised, effectively failing your test. But what about a verify? Well as mentioned, WebDriver doesn't have one. But you could still perform something equivalent by doing a comparison.
if element.text != u'Example Domains':
print"Verify Failed: element text is not %r" % element.text
So in this case, your test won't fail. But a verification will still take place and will print to stdout.
So in the end, it's a matter of what you want to fail. It's more of a test design. Hope this helps.
Solution 3:
You should use the following function to check that:
defis_element_present(self, how, what):
try: self.driver.find_element(by=how, value=what)
except NoSuchElementException as e: returnFalsereturnTrue
Which is default generated by Selenium IDE when exporting to Python code.
Then you can assert the element as below:
self.assertTrue(self.is_element_present(By.ID, "footer"))
self.assertTrue(self.is_element_present(By.CSS_SELECTOR, "header.global-header"))
Note that the following import is required to use By
:
from selenium.webdriver.common.by import By
Solution 4:
Another way is as follows:
from selenium importwebdriverdriver= webdriver.Firefox()
driver.get('http://www.testing.com')
element = driver.find_element_by_xpath('xpath of the element').text
assertelement== 'Sample Text'
driver.quit()
Solution 5:
Verify the Assert
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);
Post a Comment for "Assert/verifyelementpresent With Python And Webdriver?"