Home > Enterprise >  How to loop back if password/username is wrong and print to user
How to loop back if password/username is wrong and print to user

Time:06-25

I am currently writing in python to login to a website but want to facilitate as much user error as possible.

I want the code to print "Username/Password Incorrect" and then loop back to enter the username and password again.

Sadly I cant share the website with you as its on an intranet.

My Code:

#Enter Username
username = driver.find_element(By.NAME, value='j_username')
username.send_keys(input('Enter Username:'))

#Enter Password
password = driver.find_element(By.NAME, value='j_password')
password.send_keys(input('Enter Password:'))

I was wondering if its possible to get the error and loop back when this element is the displayed on the website:

enter image description here

Thanks for anyone who helps

CodePudding user response:

You have 2 possible scenarios: Login success and Login fail. You need to wait for the error message to appear in order to retry once it's here.

First let's import what we need

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

We can then start iterating

timeout = 5
error_msg_selector = '//div[@]' // example selector by class    

while True:
    try_login() // put your 4 lines in this function
    try:
        is_error_present = EC.presence_of_element_located((By.ID, 'element_id'))
        WebDriverWait(driver, timeout).until(is_error_present)
        print('Error message found, trying again')
        driver.refresh()
        continue
    except TimeoutException:
        print('Timed out while waiting for the error')
        break
print('We got out of the loop, login succeeded')

Note: It might be better to find an element that indicates successful login instead of the opposite, so that you don't have to check for multiple error messages.

CodePudding user response:

.current_url returns the url the driver is currently on. If you have a unique identifier in the successful login attempt you could run a while loop with a not statement in it and keep looping through until the user successfully loges in and the condition is met.

  • Related