Cal Corbin
Cal Corbin

Reputation: 188

Trouble verifying text is present in a div with Selenium/Python

So I am trying to verify text is an element, basically I'm testing what happens when no search results are found. However I'm getting the following error message every time and I cannot figure out why.

Traceback (most recent call last):
  File "test.py", line 40, in test_article_no_result_search
    assert article_results_page.is_articles_not_found(), "Articles found surprisingly."
  File "/Users/tester/Documents/Automated Tests/foobar/page.py", line 71, in is_articles_not_found
    return "No Results Available" in element.get_attribute("value")
TypeError: argument of type 'NoneType' is not iterable

HTML element I'm trying to verify

<div class="simple-div results-num-span" data-node="group_0.SimpleDiv_0">No Results Available</div>

Here is my test case from test.py

class SearchTest(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Chrome()
        self.driver.get(TestingURLS.URL)

    def test_article_no_result_search(self):
        main_page = MainPage(self.driver)
        main_page.load_page()
        main_page.click_article_search_input_clear()
        main_page.enter_no_result_search_term()
        main_page.click_article_search_button()
        article_results_page = ArticleResultsPage(self.driver)
        article_results_page.load_page()
        assert article_results_page.is_articles_not_found(), "Articles found surprisingly."

    def tearDown(self):
        self.driver.quit

Relevant function in page.py

def is_articles_not_found(self):
    element = self.driver.find_element(*SearchResultLocators.UPPER_RESULT_DISPLAY)
    return "No Results Available" in element.get_attribute("value")

Relevant locator from locators.py

class SearchResultLocators(object):
    UPPER_RESULT_DISPLAY = (By.CSS_SELECTOR, "div.simple-div.results-num-span")
    RESULT_COUNT = (By.CSS_SELECTOR, "div.num-shown")
    FIRST_ARTICLE_RESULT = (By.CSS_SELECTOR, "div.result")

Upvotes: 1

Views: 527

Answers (1)

Andersson
Andersson

Reputation: 52665

element.get_attribute("value") can be applied to input nodes of type "text". In your case it is div with child text node, so you can perform below assertion:

from selenium.webdriver.support.ui import WebDriverWait as wait
from selenium.common.exceptions import TimeoutException

def is_articles_not_found(self):
    element = self.driver.find_element(*SearchResultLocators.UPPER_RESULT_DISPLAY)
    try:
        return wait(self.driver, 3).until(lambda driver: element.text == "No Results Available")
    except TimeoutException:
        return False

Upvotes: 1

Related Questions