【问题标题】:Django selenium how to get page text using find_elementDjango selenium 如何使用 find_element 获取页面文本
【发布时间】:2014-10-14 15:18:24
【问题描述】:

我正在尝试使用 selenium 获取文本“不正确的凭据”。

这是我尝试过的......

message_text = self.driver.find_element(By.XPATH, '//*[@id="toast-container"]/div/div[1][@class="ng-binding toast-title"]')
print(message_text.text)

也试过了:

 message_text = self.driver. find_element_by_xpath('//*[@id="toast-container"]/div/div[1][@class="ng-binding toast-title"]').text

但我只得到一个空字符串。

文本只能通过 JS 添加到页面中。

知道为什么它是空白的吗?

这是渲染的 html...

<div ng-repeat="toaster in toasters" class="toast ng-scope toast-error" ng-class="toaster.type"
     ng-click="click(toaster)" ng-mouseover="stopTimer(toaster)" ng-mouseout="restartTimer(toaster)" style="">
    <button class="toast-close-button" ng-show="config.closeButton">×</button>
    <div ng-class="config.title" class="ng-binding toast-title">Incorrect Credentials</div>
    <div ng-class="config.message" ng-switch="" on="toaster.bodyOutputType" class="toast-message">
        <!-- ngSwitchWhen: trustedHtml --><!-- ngSwitchWhen: template --><!-- ngSwitchDefault:  -->
        <div ng-switch-default="" class="ng-binding ng-scope">Incorrect Email/Password</div>
    </div>
</div>

更新:

这行得通,但真的很糟糕......

    self._login_process()


    import time
    time.sleep(10)

    element = WebDriverWait(self.driver, 10).until(
        EC.presence_of_element_located((By.CLASS_NAME, "toast-title"))
    )

更新

得到这个工作......

 element = WebDriverWait(self.driver, 20).until(
            EC.text_to_be_present_in_element((By.CLASS_NAME, "toast-title"), 'Incorrect Credentials')
        )

【问题讨论】:

  • @Brandon yes 和 message_text.text 应该具有值“不正确的凭据”,但它是空白的。我错过了什么吗?
  • 您使用的是 LiveServerTestCase 吗? docs.djangoproject.com/en/1.7/topics/testing/tools/… 你应该可以使用内置的.find_element_by_id() 方法而不是XPATH
  • 我试过 self.driver.find_element_by_class_name('toast-title') 没有任何乐趣。也许我需要等一下?
  • 你肯定需要给你的 ajax / dom 操作时间来完成。对于这种类型的测试,我个人认为 QUnit 测试更容易处理。
  • @Brandon 解决了,我可以让 selenium 等待 http 状态码吗?

标签: javascript python django selenium django-testing


【解决方案1】:

1) 在检查值之前,我需要先等待 AJAX 调用完成。

2) 在创建页面时,消息框已经呈现为空白值。

要解决这个问题,我需要等到消息框中的文本发生变化...

 element = WebDriverWait(self.driver, 20).until(
            EC.text_to_be_present_in_element((By.CLASS_NAME, "toast-title"), 'Incorrect Credentials')
        )
如果在 x 秒内未找到文本 Incorrect Credentials

元素现在返回 True。我可以使用...进行检查。

 noz.assert_equal(element, True)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-13
    • 1970-01-01
    • 2018-11-01
    • 1970-01-01
    相关资源
    最近更新 更多