如何验证Selenium WebDriver中存在的动态元素

时间:2015-05-31 21:51:47

标签: python css selenium selenium-webdriver automated-tests

我正在使用Selenium WebDriver在Python中编写脚本来测试Web应用程序。

Web应用程序允许用户提出问题,这些问题会在询问时添加到div中。每个问题div都有自己的“upvote”和“downvote”链接/图像。单击“upvote”图标时,图像会发生变化,从活动状态变为非活动状态,反之亦然。我知道这个upvote图标的xpath是:

"//div[@id='recent-questions-container']/div/div/div/div/div[2]/div/ul/li/a/i"

路径末尾的“i”是一个类,将是

<i class="fa fa-2x fa-thumbs-o-up"></i>

<i class="fa fa-2x fa-thumbs-up clicked"></i>

取决于是否点击了它。我想在点击时验证是否有正确的图像。我怎样才能做到这一点?理想情况下,我想使用断言来执行此验证,la:

self.assertTrue(self.is_element_present( ... ))

以下是我正在谈论的HTML

<div id="recent-questions-container">
    <div question_id="randomly generated blah" class="q row recent-question animated pulse" data-score="0">
        <div class="col-xs-12">
        <div class="question-content">
            <p>3</p>


            <div class="row question-controls">
                <div class="owner-view hidden">
                    ...
                <div class="student-view">
                    <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 question-controls-left">
                        <ul class="list-inline">
                            <li>
                                <a href="#" class="student-view thumbs-up-to-active">
                                    <i class="fa fa-thumbs-o-up fa-2x"></i></a>
                            </li>
                            <li>
                                <span class="num-votes">0</span>
                            </li>
                            <li class="thumbs-down-li">
                                <a href="#" class="student-view thumbs-down-to-active">
                                    <i class="fa fa-thumbs-o-down fa-2x"></i></a>
                            </li>
                        </ul>
                    </div>

                </div>

            </div>
            <hr>
        </div>
    </div>
    </div>
... other questions ... 
            </div>
            <hr>
        </div>
    </div>
    </div>


            </div>

1 个答案:

答案 0 :(得分:1)

您可以使用get_attribute获取class属性,然后在该类包含点击时进行搜索以确保其实际上已点击

#make sure the selector is correct
xpath = "//div[@id='recent-questions-container']/div/div/div/div/div[2]/div/ul/li/a/i"
element = driver.find_element(By.XPATH, xpath)
attr = element.get_attribute('class')
if  'clicked' in attr:
    print("clicked")
else:
    print("was not clicked")

修改

我会点击该元素,现在应该期望将该类更改为 active 。然后找到应该大于 0

的计数
driver = self.driver
#perform click here
#the idea is to avoid the NoSuchElement exception
# and see if the element count is greater than 0
assert (len(driver.find_elements_by_css_selector(".student-view.thumbs-up-to-active")) > 0)