使用Selenium / Python在div中存在验​​证文本的问题

时间:2018-01-29 16:37:37

标签: python selenium automated-tests

所以我试图验证文本是一个元素,基本上我正在测试没有找到搜索结果时会发生什么。但是我每次都收到以下错误消息,我无法弄清楚原因。

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元素我正在尝试验证

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

以下是来自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

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")

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")

1 个答案:

答案 0 :(得分:1)

element.get_attribute("value")可以应用于input类型的"text"个节点。在您的情况下,它是div子文本节点,因此您可以执行以下断言:

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