Checking if element is present using 'By' from Selenium Webdriver and Python
python, webdriver
Solution
First of all, it's discouraged to do so, it's better to change your testing logic than finding text in page.
Here's how you create you own `is_text_present` method though, if you really want to use it:
def is_text_present(self, text):
try:
body = self.driver.find_element_by_tag_name("body") # find body tag element
except NoSuchElementException, e:
return False
return text in body.text # check if the text is in body's text
For images, the logic is you pass the locator into it. (I don't think `is_element_present` exists in WebDriver API though, not sure how you got `By.ID` working, let's assume it's working.)
self.assertTrue(self.is_element_present(By.ID, "the id of your image"))
# alternatively, there are others like CSS_SELECTOR, XPATH, etc.
# self.assertTrue(self.is_element_present(By.CSS_SELECTOR, "the css selector of your image"))
Problem
I am attempting to validate that text is present on a page. Validating an element by ID is simple enough, buy trying to do it with text isn't working right. And, I can not locate the correct attribute for By to validate text on a webpage. Example that works for ID using By attribute ``` self.assertTrue(self.is_element_present(By.ID, "FOO")) ``` Example I am trying to use (doesn't work) for text using By attribute ``` self.assertTrue(self.is_element_present(By.TEXT, "BAR")) ``` I've tried these as well, with *error (below) ``` self.assertTrue(self.is_text_present("FOO")) ``` and ``` self.assertTrue(self.driver.is_text_present("FOO")) ``` *error: AttributeError: 'WebDriver' object has no attribute 'is_element_present' I have the same issue when trying to validate `By.Image` as well.