简体   繁体   中英

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.

Any idea why it is blank?

This is the rendered 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

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.

2) The message box was already rendered with a blank value on creation of the page.

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. I can check for this using...

 noz.assert_equal(element, True)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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