Skip to content
Advertisement

Python Selenium Logon

This code technically works to login just fine. However, on successful login it prints both login successful, and login incorrect. on failed login it only prints login incorrect.

I’m using python3, and selenium. I believe this may be a syntax error, but I’m just not sure how to fix it. I can hard-code the credentials of course, but want this to be usable by multiple parties.

   loginGood = #The page after login
   loginBad = #The login page
   loginCheck = driver.current_url

   while loginCheck == loginBad:
   try:
       loginName = driver.find_element_by_xpath('//*[@id="user_name"]')
       print('Please enter your username: ')
       userName = input("Username: "+'')
       loginName.send_keys(userName)
       print('Please enter your password: ')
       passWord = getpass("Password: "+'')
       loginPass = driver.find_element_by_xpath('//*[@id="password"]')
       loginPass.send_keys(passWord)

   except:
       print('Login Successful')
       break
   else:
       print('login incorrect')
       continue

Advertisement

Answer

I think this is what you are attempting to do.

while loginCheck == loginBad:
    try:
        loginName = driver.find_element_by_xpath('//*[@id="user_name"]')
        print('Please enter your username: ')
        userName = input("Username: "+'')
        loginName.send_keys(userName)
        print('Please enter your password: ')
        passWord = getpass("Password: "+'')
        loginPass = driver.find_element_by_xpath('//*[@id="password"]')
        loginPass.send_keys(passWord)
        print('Login Successful')
        break
    except:
        print('login incorrect')

Note, this will be a continuous loop if always incorrect, you may want to consider wrapping in a for loop with a range.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement