Home > database >  Loop Error Handling / Loop not breaking when condition met with selenium / python
Loop Error Handling / Loop not breaking when condition met with selenium / python

Time:08-17

Creating a script that will pull user information from AD and pass that information into a automation program that generates user accounts for a webpage. I have been able to get through the entire webpage but I am running into a issue with the script handling a username error. Basically if the username is already taken I want it to add a 1 to the end of the user name. If the user name with a one is taken I want it to backspace and add a 2 etc until the error no longer pops up. Once that happens I want to skip the rest of the loop and move on through the rest of the code. I use a IF statement to put the 1 behind the user name. Then a while loop to add a 2-10 if needed along with a IF statement in the while loop to BREAK if the condition is met and then a else statement to continue. It keeps getting hung up if the username doesn't need a number added or if the account only needs a 1 added. When it get hung I get a ```TimeoutException error``, I want it to continue through the rest of the code if the conditions have been met. I have placed the code below.

Please let me know if you need any additional info. Also please let me know if you see anything that I could clean up to make the script run better.

Selenium Python Script

import time
from xmlrpc.client import boolean
import win32clipboard
from hashlib import new
from multiprocessing.connection import wait
from select import select
from webbrowser import BaseBrowser, Chrome
from xml.etree.ElementPath import find
import win32com.client as win32

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.keys import Keys

import ADTest

options = webdriver.ChromeOptions()
options.add_experimental_option('excludeSwitches', ['enable-logging'])
driver = webdriver.Chrome(options=options) 
driver.get('https://power.dat.com')

# chrome_optinons = webdriver.ChromeOptions()
# chrome_optinons.add_argument('--headless')
# chrome_optinons.add_argument('window-size=1920x1080')

#setup wait 
wait = WebDriverWait(driver, 10)

Logon = driver.find_element(By.XPATH, '//*[@id="mat-input-1"]')
Logon.send_keys('')

password = driver.find_element(By.XPATH, '//*[@id="mat-input-0"]')
password.send_keys('')

loginbutton = driver.find_element(By.XPATH, '//*[@id="submit-button"]')
loginbutton.click()

(time.sleep(2))

profiledrop = driver.find_element(By.XPATH, '//*[@id="user-salutation"]')
profiledrop.click()

#store original window ID
windows_before = driver.current_window_handle

Adminbutton = driver.find_element(By.CSS_SELECTOR, '#userPreferencesUl > li:nth-child(5) > a')
Adminbutton.click()

#Wait for new window Tab
WebDriverWait(driver, 10).until(EC.number_of_windows_to_be(2))

windows_after = driver.window_handles

new_window = [x for x in windows_after if x != windows_before][0]

#driver.switch_to.window(new_window)
driver.switch_to.window(driver.window_handles[1])
#Tells program to wait till new window confirmed 
WebDriverWait(driver,20).until(EC.title_is("Admin"))

(time.sleep(5))

#New User Button
WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.XPATH, "//button[normalize-space()='Create New User']"))).click()

#User Name
UserName = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@name='loginId']")))
UserName.send_keys("TQL"   ADTest.DatUsrName)

#Password 
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@name='password']"))).send_keys("total2")

#Confirm Password
element = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@name='confirmPassword']")))
element.send_keys("total2")

#State
state = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//select[@name='state']")))
selectState = Select(state)
selectState.select_by_value('string:'   ADTest.DATST)

#First Name
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@name='firstName']"))).send_keys(ADTest.FirstN)

#Last Name
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@name='lastName']"))).send_keys(ADTest.LastN)

#Workgroup ID
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@name='initials']"))).send_keys(ADTest.DATint)

#Phone Number 
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@name='primaryPhone']"))).send_keys("8005803101")

#Extension
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@name='primaryExtension']"))).send_keys(ADTest.ext)

#Email
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@name='email']"))).send_keys(ADTest.email)

#National Account: Combo Premium Pooling Subscription 
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//label[contains(text(),'National Account: Combo Premium Pooling Subscripti')]"))).click()

#National Account: Combo Premium Pooling Subscription 
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//label[normalize-space()='National Account: DAT Connexion Subscription']"))).click()

#National Account: Combo Premium Pooling Subscription 
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//label[normalize-space()='National Account: Power Broker Subscription']"))).click()

UserName.send_keys(Keys.CONTROL, 'a')
UserName.send_keys(Keys.CONTROL, 'c')

count = 1 
# #Submit Button 
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[normalize-space()='Add User']"))).click()

if WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.XPATH, '//div[@class= "error-section"]//p[contains(.,"Sorry, something unexpected happened. Please try again.")]'))):
   WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="data"]/div[1]/button'))).click()
   UserName.send_keys("1")
   UserName.send_keys(Keys.CONTROL, 'a')
   UserName.send_keys(Keys.CONTROL, 'c')

   WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[normalize-space()='Add User']"))).click()
   while (WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.XPATH, '//div[@class= "error-section"]//p[contains(.,"Sorry, something unexpected happened. Please try again.")]'))) == True) :
      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="data"]/div[1]/button'))).click()
      UserName.send_keys(Keys.BACK_SPACE)
      count = count   1
      UserName.send_keys(count)
      UserName.send_keys(Keys.CONTROL, 'a')
      UserName.send_keys(Keys.CONTROL, 'c')
      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[normalize-space()='Add User']"))).click()

      if (WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.XPATH, '//div[@class= "error-section"]//p[contains(.,"Sorry, something unexpected happened. Please try again.")]'))) == False):
       break

      else:
         continue

new_url = ('https://power.dat.com')

driver.execute_script("window.open(' ');")

driver.switch_to.window(driver.window_handles[2])
driver.get(new_url)

profiledrop = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="user-salutation"]')))
profiledrop.click()

#(time.sleep(2))

driver.find_element(By.XPATH, '//a[@id="logout"]').click()

win32clipboard.OpenClipboard()
NewUserName = win32clipboard.GetClipboardData()

(time.sleep(3))

driver.find_element(By.XPATH, '//*[@id="mat-input-1"]').send_keys(NewUserName)

driver.find_element(By.XPATH, '//*[@id="mat-input-0"]').send_keys('total2')

driver.find_element(By.XPATH, '//*[@id="submit-button"]').click()

confirm = (WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//a[@id='user-salutation']"))).get_attribute("innerHTML"))


if confirm == ("Hi "   NewUserName):
   print("User Account Created")
   outlook = win32.Dispatch('outlook.application')
   mail = outlook.CreateItem(0)
   mail.To = ADTest.email
   mail.Subject = "DAT Account Information"
   mail.Body = (ADTest.FirstN   " your DAT account has been created!\n \n"   "Please see the log in info below:\n \n"
            "Username: "   NewUserName   "\nPassword: total2 \n\n"
            "You can log in with the below link \n"
            "https://power.dat.com")
   mail.Send()
else:
   print("Issue occured could not confirm user account created, please confirm creation was succesful")

driver.quit()

The loop where the script has trouble

UserName.send_keys(Keys.CONTROL, 'a')
UserName.send_keys(Keys.CONTROL, 'c')

count = 1 
# #Submit Button 
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[normalize-space()='Add User']"))).click()

if WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.XPATH, '//div[@class= "error-section"]//p[contains(.,"Sorry, something unexpected happened. Please try again.")]'))):
   WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="data"]/div[1]/button'))).click()
   UserName.send_keys("1")
   UserName.send_keys(Keys.CONTROL, 'a')
   UserName.send_keys(Keys.CONTROL, 'c')

   WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[normalize-space()='Add User']"))).click()
   while (WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.XPATH, '//div[@class= "error-section"]//p[contains(.,"Sorry, something unexpected happened. Please try again.")]'))) == True) :
      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="data"]/div[1]/button'))).click()
      UserName.send_keys(Keys.BACK_SPACE)
      count = count   1
      UserName.send_keys(count)
      UserName.send_keys(Keys.CONTROL, 'a')
      UserName.send_keys(Keys.CONTROL, 'c')
      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[normalize-space()='Add User']"))).click()

      if (WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.XPATH, '//div[@class= "error-section"]//p[contains(.,"Sorry, something unexpected happened. Please try again.")]'))) == False):
       break

      else:
         continue

CodePudding user response:

I figured this out needed to add a try on the initial button click please see below.

count = 0 
# #Submit Button 
try:
      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[normalize-space()='Add User']"))).click()

      while True:
         WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, '//div[@class= "error-section"]//p[contains(.,"Sorry, something unexpected happened. Please try again.")]')))
         WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="data"]/div[1]/button'))).click()
         UserName.send_keys(Keys.BACK_SPACE)
         count = count   1
         UserName.send_keys(count)
         UserName.send_keys(Keys.CONTROL, 'a')
         UserName.send_keys(Keys.CONTROL, 'c')   
         WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[normalize-space()='Add User']"))).click()
         time.sleep(3)
         
except TimeoutException:
      print("no error")
            
finally:
      new_url = ('https://power.dat.com')
      driver.execute_script("window.open(' ');")
      driver.switch_to.window(driver.window_handles[2])
      driver.get(new_url)
profiledrop = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="user-salutation"]')))
profiledrop.click()
driver.find_element(By.XPATH, '//a[@id="logout"]').click()
win32clipboard.OpenClipboard()
NewUserName = win32clipboard.GetClipboardData()
(time.sleep(3))
driver.find_element(By.XPATH, '//*[@id="mat-input-1"]').send_keys(NewUserName)
driver.find_element(By.XPATH, '//*[@id="mat-input-0"]').send_keys('total2')
driver.find_element(By.XPATH, '//*[@id="submit-button"]').click()
  • Related