Prometheus
Prometheus

Reputation: 33615

How to get text generated by JS in Selenium?

I am trying to get the text "Incorrect Credentials" which is placed on page (js) when the user enters an incorrect user name and password...

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")

I have set a wait time of 10 seconds to make sure the element is on the page, but my test still fails with....

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

+ Incorrect Credentials

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>

How can I get this to work in Selenium?

Upvotes: 0

Views: 1416

Answers (2)

David M
David M

Reputation: 84

I'm unable to comment on rts's question

@@erthalion How to get the xpath of toaster messages.

because I don't have enough reputation points. The answer is:

Right before clicking the login button do this:

  1. Open DevTools -> Elements tab

  2. Create a breakpoint at the body tag, or even better: the parent tag of the element you are trying to find, select break on subtree modifications

  3. Press F8

  4. Click "Login"

  5. Then step through until the toastr is in view

  6. Inspect the toastr and retrieve xpath/cssSelector

Like so I can get enough reputation points so I can actually comment on things :D

Upvotes: 1

erthalion
erthalion

Reputation: 3244

You can use an explicit waiting (it works every time in my case):

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"]'))
)

Upvotes: 1

Related Questions