简体   繁体   English

Django Selenium如何使用find_element获取页面文本

[英]Django selenium how to get page text using find_element

I am trying to get the the text 'Incorrect Credentials' using selenium. 我正在尝试使用硒获取文本“不正确的凭据”。

This is what I have tried... 这就是我尝试过的...

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

also tried: 还尝试了:

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

But I just get an empty string. 但是我只是得到一个空字符串。

The text only gets added to the page via JS. 文本仅通过JS添加到页面。

Any idea why it is blank? 知道为什么它空白吗?

This is the rendered html... 这是渲染的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>

UPDATE: 更新:

This works, but is really bad.... 这可行,但确实很糟糕。

    self._login_process()


    import time
    time.sleep(10)

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

UPDATE UPDATE

Got this to work with... 可以使用...

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

1) I needed to wait for the AJAX call to complete first before check for the value. 1)我需要先等待AJAX​​调用完成,然后再检查该值。

2) The message box was already rendered with a blank value on creation of the page. 2)在创建页面时,该消息框已经使用空白值呈现。

To resolve this I needed to wait until the text in the message box changed... 为了解决这个问题,我需要等到消息框中的文本更改为止。

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

element now returns True if the text Incorrect Credentials is not found within x seconds. 如果在x秒内未找到文本“ Incorrect Credentials则元素现在返回True I can check for this using... 我可以使用...检查

 noz.assert_equal(element, True)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM