使用Selenium/Python验证div中存在文本时出现问题

使用Selenium/Python验证div中存在文本时出现问题,python,selenium,automated-tests,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

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

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

element.get\u属性(“值”)
可应用于
输入
类型为
文本的节点。在您的例子中,它是带有子文本节点的
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

似乎是
元素。get_attribute(“value”)
返回
None
,这意味着
元素中没有属性
value
。在我使用“value”验证div中的文本之前,这就是为什么这会让我感到不快的原因。因此,我根据您的建议尝试了以下内容@Andersson-
def is_articles\u not\u found(self):element=self.driver.find_element(*SearchResultLocators.RESULT_COUNT)return element.text==“Showing 0 results”
,但在我的主测试中仍然出现此断言错误-
回溯(最近一次调用):文件“test.py”,第40行,在测试文章\u no\u RESULT\u搜索断言文章\u results\u页面中。是否找到了\u文章(),“意外发现的文章。”AssertionError:意外发现的文章。
这个元素最初出现在DOM中吗?如果是,它是否包含文本或在某些操作后显示文本?是的,但在输入搜索后文本会发生更改,不会返回任何结果。请检查更新的代码。这里我们正在等待
div
节点的文本变为
“无可用结果”
并返回
True
。如果文本在3秒内未更改-返回
False
非常感谢!!这就解决了问题。
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