【问题标题】:How to get text generated by JS in Selenium?如何在 Selenium 中获取 JS 生成的文本?
【发布时间】:2014-10-13 12:04:45
【问题描述】:

当用户输入错误的用户名和密码时,我正在尝试获取放置在页面 (js) 上的文本“Incorrect Credentials”...

login_button.click()
self.driver.implicitly_wait(10) # seconds
get_conformation_message = self.driver.find_element(By.XPATH, '//*[@id="toast-container"]/div/div[1]')
noz.assert_equal(get_conformation_message.text, "Incorrect Credentials")

我已将等待时间设置为 10 秒,以确保该元素在页面上,但我的测试仍然失败,并显示......

noz.assert_equal(get_conformation_message.text, "Incorrect Credentials") nose.proxy.AssertionError: '' != 'Incorrect Credentials'

+ 不正确的凭据

这是渲染的 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>

我怎样才能让它在 Selenium 中工作?

【问题讨论】:

  • 您确定get_confirmation_message 代表您需要的对象吗?

标签: javascript python selenium


【解决方案1】:

您可以使用显式等待(在我的情况下每次都有效):

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

WebDriverWait(self.driver, 10).until(
    EC.presence_of_element_located((By.XPATH, '//*[@id="toast-container"]/div/div[1][@class="ng-binding toast-title"]'))
)

【讨论】:

  • @@erthalion 如何获取 toaster 消息的 xpath。
  • 在我的场景中,烤面包机消息在几秒钟后消失,因此无法获取烤面包机的 xpath。
【解决方案2】:

我无法评论 rts 的问题

@@erthalion 如何获取 toaster 消息的 xpath。

因为我没有足够的声望点。答案是:

在单击登录按钮之前执行以下操作:

  1. 打开 DevTools -> 元素选项卡

  2. 在body标签处创建断点,甚至更好:你要查找的元素的父标签,在子树修改时选择break

  3. 按 F8

  4. 点击“登录”

  5. 然后逐步前进,直到看到烤面包机

  6. 检查 toastr 并检索 xpath/cssSelector

这样我就可以获得足够的声望点,这样我就可以对事情发表评论了:D

【讨论】:

    猜你喜欢
    • 2021-05-19
    • 2021-04-26
    • 2013-09-05
    • 2010-12-31
    • 2015-02-13
    • 2020-08-19
    • 1970-01-01
    • 1970-01-01
    • 2020-11-18
    相关资源
    最近更新 更多