How to use focus_element method in toolium

Best Python code snippet using toolium_python

workday_apply.py

Source:workday_apply.py Github

copy

Full Screen

1from random import random2from time import sleep, time3import sys4from selenium import webdriver5from selenium.webdriver.common.by import By6from selenium.webdriver.common.keys import Keys7from datetime import date, timedelta8from keyword_config import get_response, cred_dict, RESUME_PATH9from process_label_text import process_label_text10from selenium.webdriver.common.action_chains import ActionChains11def simulate_typing(element, text, delay=0.1):12 text = str(text) # to ensure that default input such as int or float is iterable13 for character in text:14 element.send_keys(character)15 sleep(delay + (random() / 10.0))16# exists due to information not being readily available on the page. dropdown and multiinput will use this late17# and when data modification is necessary18def get_button_group_dropdown(focus_element, driver):19 button_group = None20 try:21 print("CLICKING DROPDOWN")22 root_button = focus_element.find_element(By.XPATH, ".//button[@aria-haspopup='listbox']")23 driver.execute_script("arguments[0].click();", root_button)24 sleep(4 + random())25 root_button2 = focus_element.find_element(By.XPATH, ".//button[@aria-haspopup='listbox']")26 print("is dropdown expanded?", root_button2.get_attribute('aria-expanded'))27 listbox_ul_id = root_button2.get_attribute('aria-controls')28 listbox_ul = driver.find_element(By.XPATH, ".//ul[@id='" + listbox_ul_id + "']")29 button_group = listbox_ul.find_elements(By.TAG_NAME, "li") # can just click elements30 except Exception as e:31 print(e, "get_button_group error finding dropdown")32 sleep(1 + random())33 return button_group34# should probably not try to assign button group yet, only assign when attempting to assign values.35# this is due to listbox information not being readily available on the page.36# it is mandatory to click to get info from the popup37def derive_input_type(item, driver):38 focus_element = None39 button_group = None40 THE_TYPE = ""41 # formfield- contains dropdown, text, radio, or checkbox42 try:43 focus_element = item44 try:45 item.find_element(By.XPATH, ".//button[@aria-haspopup='listbox']")46 THE_TYPE = "DROPDOWN"47 except:48 # print("derive error finding dropdown")49 try:50 button_group = focus_element.find_elements(By.XPATH, ".//input[@type='text']")51 if len(button_group) == 0:52 raise Exception("")53 THE_TYPE = "TEXT"54 except:55 # print("derive error finding text inputs")56 try:57 button_group = focus_element.find_elements(By.XPATH, ".//input[@type='radio']")58 if len(button_group) == 0:59 raise Exception("")60 THE_TYPE = "RADIO"61 except:62 # print("derive error finding radio inputs")63 try:64 button_group = focus_element.find_elements(By.XPATH, ".//input[@type='checkbox']")65 if len(button_group) == 0:66 raise Exception("")67 THE_TYPE = "CHECKBOX"68 except:69 pass70 # print("derive error finding checkbox inputs")71 if THE_TYPE == "":72 raise Exception("derive error finding dropdown, radio, checkbox, or text inputs")73 except Exception as e:74 print(e)75 try:76 focus_element = item.find_element(By.TAG_NAME, "textarea")77 THE_TYPE = "TEXTAREA"78 except:79 # print("derive error finding textarea input")80 try:81 item.find_element(By.XPATH, ".//div[@data-automation-id='dateInputWrapper']")82 focus_element = item83 THE_TYPE = "DATE"84 except:85 # print("derive error finding date")86 try:87 item.find_element(By.XPATH, ".//div[@data-automation-id='multiselectInputContainer']")88 focus_element = item89 THE_TYPE = "MULTIINPUT"90 except:91 print("derive error finding multiinput, or unknown type")92 return [focus_element, button_group, THE_TYPE]93def is_input_field_empty(FOCUS_ELEMENT, BUTTON_GROUP, INPUT_TYPE, driver):94 ret_list = []95 if INPUT_TYPE == "RADIO" or INPUT_TYPE == "CHECKBOX":96 id_text_list = []97 for button in BUTTON_GROUP:98 if button.get_attribute('aria-checked') == 'true':99 id_text_list.append(button.get_attribute('id'))100 # translate radio button ids into label text101 for button_id_text in id_text_list:102 ret_list.append(FOCUS_ELEMENT.find_element(By.XPATH, ".//label[@for='" + button_id_text + "']").text)103 elif INPUT_TYPE == "TEXTAREA":104 some_str = FOCUS_ELEMENT.text105 if some_str.replace(' ', '').replace('\n', '') != '':106 ret_list.append(some_str)107 elif INPUT_TYPE == "DROPDOWN":108 dropdown = FOCUS_ELEMENT.find_element(By.XPATH, ".//button[@aria-haspopup='listbox']")109 if dropdown.get_attribute('value') != "":110 ret_list.append(dropdown.text)111 elif INPUT_TYPE == "MULTIINPUT":112 try:113 multi_item = FOCUS_ELEMENT.find_element(By.XPATH, ".//div[starts-with(@id, 'pill-')]")114 ret_list.append(multi_item.text)115 except:116 print("couldnt find multiitem")117 elif INPUT_TYPE == "DATE":118 try:119 mm_ele = FOCUS_ELEMENT.find_element(By.XPATH, ".//input[@aria-label='Month']")120 mm_str = mm_ele.get_attribute('aria-valuetext')121 except:122 mm_str = ""123 try:124 dd_ele = FOCUS_ELEMENT.find_element(By.XPATH, ".//input[@aria-label='Day']")125 dd_str = dd_ele.get_attribute('aria-valuetext')126 except:127 dd_str = ""128 try:129 yyyy_ele = FOCUS_ELEMENT.find_element(By.XPATH, ".//input[@aria-label='Year']")130 yyyy_str = yyyy_ele.get_attribute('aria-valuetext')131 except:132 yyyy_str = ""133 if len(dd_str) == 1:134 dd_str = "0" + dd_str135 if len(mm_str) == 1:136 mm_str = "0" + mm_str137 full_date_str = mm_str + dd_str + yyyy_str138 # all strings must be numeric to be considered selected139 print("full_date_str", full_date_str)140 if full_date_str.isnumeric():141 ret_list.append(mm_str + "//" + dd_str + "//" + yyyy_str)142 elif INPUT_TYPE == "TEXT":143 some_str = BUTTON_GROUP[0].get_attribute('value')144 if some_str is not None and some_str.replace(' ', '') != '':145 ret_list.append(some_str)146 else:147 ret_list.append("NOT INITIALIZED, TREATING AS A FINISHED ITEM")148 print("unknown type in get_empty_question_items, USING PLACEHOLDER TO IGNORE")149 print("is_input_field_empty:", ret_list)150 if len(ret_list) == 0:151 return True152 return False153def resolve_input(driver, item, response):154 DEFAULT_INPUT = 1155 DEFAULT_DATE = date.today()156 derived = derive_input_type(item, driver)157 FOCUS_ELEMENT = derived[0]158 BUTTON_GROUP = derived[1]159 INPUT_TYPE = derived[2]160 if INPUT_TYPE == "DROPDOWN":161 BUTTON_GROUP = get_button_group_dropdown(FOCUS_ELEMENT, driver)162 elif INPUT_TYPE == "MULTIINPUT":163 BUTTON_GROUP = None164 if BUTTON_GROUP is not None:165 BUTTON_GROUP = BUTTON_GROUP[::-1]166 print("resolve_input function given:", response, "\nFocus element:", FOCUS_ELEMENT.text, BUTTON_GROUP, INPUT_TYPE)167 try:168 if INPUT_TYPE == "RADIO":169 clicked_a_button = False170 if response is not None:171 if not clicked_a_button:172 for button in BUTTON_GROUP:173 print(button.text)174 # button does not contain text, but only the id175 button_id_text = button.get_attribute('id')176 answer_text = FOCUS_ELEMENT.find_element(By.XPATH,177 ".//label[@for='" + button_id_text + "']").text178 print(button_id_text, answer_text)179 print("RESPONSE:", response)180 if response.lower() == answer_text.lower():181 driver.execute_script("arguments[0].click();", button)182 clicked_a_button = True183 break184 if not clicked_a_button:185 for button in BUTTON_GROUP:186 print(button.text)187 # button does not contain text, but only the id188 button_id_text = button.get_attribute('id')189 answer_text = FOCUS_ELEMENT.find_element(By.XPATH, ".//label[@for='" + button_id_text + "']").text190 print(button_id_text, answer_text)191 print("RESPONSE:", response)192 if response is not None and response.lower() in answer_text.lower():193 driver.execute_script("arguments[0].click();", button)194 clicked_a_button = True195 break196 if not clicked_a_button:197 driver.execute_script("arguments[0].click();", BUTTON_GROUP[0])198 elif INPUT_TYPE == "CHECKBOX":199 clicked_a_button = False200 for button in BUTTON_GROUP:201 print(button.text)202 # button does not contain text, but only the id203 button_id_text = button.get_attribute('id')204 answer_text = FOCUS_ELEMENT.find_element(By.XPATH, ".//label[@for='" + button_id_text + "']").text205 print(button_id_text, answer_text)206 print("RESPONSE:", response)207 # checkboxes should rely on dictionary indexing only208 if clicked_a_button:209 response = None210 if response is not None and response.lower() in answer_text.lower():211 driver.execute_script("arguments[0].click();", button)212 clicked_a_button = True213 else:214 processed_text = process_label_text(answer_text)215 processed_text_list = processed_text.lower().split()216 response = get_response(processed_text, processed_text_list, INDEXING="DICTIONARY")217 if response is not None:218 sleep(1 + random())219 driver.execute_script("arguments[0].click();", button)220 clicked_a_button = True221 if not clicked_a_button:222 driver.execute_script("arguments[0].click();", BUTTON_GROUP[0])223 elif INPUT_TYPE == "TEXTAREA":224 if response is not None:225 FOCUS_ELEMENT.click()226 FOCUS_ELEMENT.clear()227 simulate_typing(FOCUS_ELEMENT, response)228 FOCUS_ELEMENT.sendKeys(Keys.TAB)229 else:230 FOCUS_ELEMENT.click()231 FOCUS_ELEMENT.clear()232 simulate_typing(FOCUS_ELEMENT, DEFAULT_INPUT)233 FOCUS_ELEMENT.sendKeys(Keys.TAB)234 elif INPUT_TYPE == "TEXT":235 if response is not None:236 BUTTON_GROUP[0].click()237 BUTTON_GROUP[0].clear()238 simulate_typing(BUTTON_GROUP[0], response)239 BUTTON_GROUP[0].sendKeys(Keys.TAB)240 else:241 BUTTON_GROUP[0].click()242 BUTTON_GROUP[0].clear()243 simulate_typing(BUTTON_GROUP[0], DEFAULT_INPUT)244 BUTTON_GROUP[0].sendKeys(Keys.TAB)245 elif INPUT_TYPE == "DROPDOWN":246 options = BUTTON_GROUP247 print("REACHED DROPDOWN INPUTTING, response:", response)248 try:249 if response is not None:250 made_selection = False251 # attempt to find exact match252 for op in options:253 print(response, op.text)254 if response.lower() == op.text.lower():255 driver.execute_script("arguments[0].click();", op)256 made_selection = True257 break258 if not made_selection:259 for op in options:260 print(response, op.text)261 if response.lower() in op.text.lower():262 driver.execute_script("arguments[0].click();", op)263 made_selection = True264 break265 if not made_selection:266 driver.execute_script("arguments[0].click();", options[0])267 else:268 driver.execute_script("arguments[0].click();", options[0])269 except Exception as e:270 print(e, "error at trying to select in dropdown")271 elif INPUT_TYPE == "MULTIINPUT":272 # can be expressed as a tree273 # sometimes, the depth is deeper than one274 # very finicky. selenium locators have issues finding promptLeafNodes on the end leafs275 actions = ActionChains(driver)276 if is_input_field_empty(FOCUS_ELEMENT, BUTTON_GROUP, INPUT_TYPE, driver):277 # some will not populate results on click, send keys becomes mandatory278 driver.execute_script("arguments[0].click();", FOCUS_ELEMENT)279 focus_input = FOCUS_ELEMENT.find_element(By.XPATH, ".//input")280 if response is not None:281 focus_input.send_keys(response)282 else:283 focus_input.send_keys(DEFAULT_INPUT)284 sleep(1)285 actions.send_keys(Keys.ENTER).perform()286 sleep(2)287 actions.send_keys(Keys.ENTER).perform()288 sleep(1)289 # there are two known types of multiinput, one is a click through, and the other is a checkbox list290 # checkbox list requires manual closing of the popup291 try:292 # if the search results popup is still open, then click the button to close it293 driver.find_element(By.XPATH, "//div[@data-automation-widget='wd-popup']")294 close_popup = driver.find_element(By.XPATH, "//span[@data-automation-id='promptSearchButton']")295 driver.execute_script("arguments[0].click();", close_popup)296 sleep(1)297 except:298 print("multiinput popup query not found")299 elif INPUT_TYPE == "DATE":300 driver.execute_script("arguments[0].click();", FOCUS_ELEMENT)301 try:302 sleep(1) # /..//div[@data-automation-id='spinnerDisplay']303 mm_ele = FOCUS_ELEMENT.find_element(By.XPATH, ".//input[@aria-label='Month']")304 driver.execute_script("arguments[0].click();", mm_ele)305 sleep(1)306 mm_ele.send_keys(DEFAULT_DATE.strftime("%m"))307 except:308 print("month not found")309 try:310 sleep(1)311 dd_ele = FOCUS_ELEMENT.find_element(By.XPATH, ".//input[@aria-label='Day']")312 driver.execute_script("arguments[0].click();", dd_ele)313 sleep(1)314 dd_ele.send_keys(DEFAULT_DATE.strftime("%d"))315 except:316 print("day not found")317 try:318 sleep(1)319 yyyy_ele = FOCUS_ELEMENT.find_element(By.XPATH, ".//input[@aria-label='Year']")320 driver.execute_script("arguments[0].click();", yyyy_ele)321 sleep(1)322 yyyy_ele.send_keys(DEFAULT_DATE.strftime("%Y"))323 except:324 print("year not found")325 else:326 print("unknown input type or blank")327 except Exception as e:328 print(e, "error resolving input")329def solve_items(driver, the_items):330 for item in the_items:331 sleep(2 + random())332 question_text = ""333 try:334 question_text = item.find_element(By.XPATH, ".//label[starts-with(@for, 'input-')]").text335 except:336 # where date is different337 try:338 question_text = item.find_element(By.XPATH, ".//label[starts-with(@id, 'label-')]").text339 except:340 print("question text error")341 processed_text = process_label_text(question_text)342 question_text_list = processed_text.lower().split()343 response = get_response(question_text, question_text_list, INDEXING="TEXT")344 # need to figure out how to differentiate inputs345 resolve_input(driver, item, response)346def get_empty_question_items(question_items):347 empty_question_items = []348 for item in question_items:349 try:350 derived = derive_input_type(item, driver)351 FOCUS_ELEMENT = derived[0]352 BUTTON_GROUP = derived[1]353 INPUT_TYPE = derived[2]354 print(FOCUS_ELEMENT.text, BUTTON_GROUP, INPUT_TYPE)355 # questions without an answer list will return [] which is getting appended356 # using placeholder in get_input_field_values to ignore questions without an answer list357 if is_input_field_empty(FOCUS_ELEMENT, BUTTON_GROUP, INPUT_TYPE, driver):358 empty_question_items.append(item)359 except Exception as e:360 print(e, "error get_empty_question_items item")361 display_list = []362 for item in empty_question_items:363 display_list.append(item.text)364 print("empty q items:", display_list)365 return empty_question_items366def get_required_question_items(question_items):367 req_question_items = []368 for item in question_items:369 try:370 item_label = item.find_element(By.XPATH, ".//abbr[@title='required']")371 req_question_items.append(item)372 except Exception as e:373 print("couldn't find required for item\n")374 return req_question_items375def solve_questions(driver):376 sleep(2 + random())377 # gather all question items data-automation-id378 try:379 base_question_items = driver.find_elements(By.XPATH, "//div[starts-with(@data-automation-id, 'formField-')]")380 required_question_items = get_required_question_items(base_question_items)381 empty_question_items = get_empty_question_items(required_question_items)382 solve_items(driver, empty_question_items)383 except Exception as e:384 print(e, "error at aria-invalid")385# returns True on login386def login(driver, EMAIL, PASSWORD):387 sleep(5 + random())388 try:389 email_input = driver.find_element(By.XPATH, "//input[@data-automation-id='email']")390 password_input = driver.find_element(By.XPATH, "//input[@data-automation-id='password']")391 email_input.send_keys(EMAIL)392 password_input.send_keys(PASSWORD)393 sleep(.3)394 submit_button = driver.find_element(By.XPATH, "//div[@data-automation-id='noCaptchaWrapper']")395 submit_button.click()396 # check to see if continue button exists397 sleep(20 + random())398 driver.find_element(By.XPATH, "//button[@data-automation-id='bottom-navigation-next-button']")399 except Exception as e:400 print(e, "error at login, attempting create acc")401 try:402 sleep(1 + random())403 create_acc_button = driver.find_element(By.XPATH, "//button[@data-automation-id='createAccountLink']")404 create_acc_button.click()405 sleep(1 + random())406 email_input = driver.find_element(By.XPATH, "//input[@data-automation-id='email']")407 password_input = driver.find_element(By.XPATH, "//input[@data-automation-id='password']")408 verify_password_input = driver.find_element(By.XPATH, "//input[@data-automation-id='verifyPassword']")409 try:410 create_acc_checkbox = driver.find_element(By.XPATH,411 "//input[@data-automation-id='createAccountCheckbox']")412 create_acc_checkbox.click()413 except:414 print("create acc checkbox not found")415 email_input.send_keys(EMAIL)416 password_input.send_keys(PASSWORD)417 verify_password_input.send_keys(PASSWORD)418 sleep(1 + random())419 submit_button = driver.find_element(By.XPATH, "//div[@data-automation-id='noCaptchaWrapper']")420 submit_button.click()421 # check to see if continue button exists422 sleep(20 + random())423 driver.find_element(By.XPATH, "//button[@data-automation-id='bottom-navigation-next-button']")424 # on some websites, it requires email verification425 alert_msg = driver.find_element(By.XPATH, "//button[@data-automation-id='alertMessage']")426 if "An email has been sent to you. Please verify your account." in alert_msg.text:427 # need to login to email and press verify428 print("Need to click verification link")429 return False430 except Exception as e:431 print(e, "login form detection issue")432 return False433 return True434def apply(driver):435 # wait until apply button appears436 sleep(6 + random())437 applied = False438 APPLY_TIMEOUT = 600439 try:440 err_msg = driver.find_element(By.XPATH, "//span[@data-automation-id='errorMessage']")441 if err_msg.text.lower() == "the page you are looking for does not exist":442 applied = True443 print("Page does not exist")444 return applied445 else:446 print("page seems valid, but has error message")447 except Exception as e:448 print("page seems valid")449 try:450 try:451 apply_button = driver.find_element(By.XPATH, "//a[@data-automation-id='adventureButton']")452 driver.execute_script("arguments[0].click();", apply_button)453 sleep(4 + random())454 except Exception as e:455 print(e, "apply button")456 return applied457 try:458 autofill_w_resume_button = driver.find_element(By.XPATH, "//a[@data-automation-id='autofillWithResume']")459 autofill_w_resume_button.click()460 except Exception as e:461 print(e, "autofill w resume button")462 return applied463 # sometimes login isn't neccessary to apply for a job464 login_status = login(driver, cred_dict['email'], cred_dict['password'])465 print("login status:", login_status)466 try:467 driver.find_element(By.XPATH, "//div[@data-automation-id='alreadyApplied']")468 applied = True469 return applied470 except:471 print("couldnt find already applied")472 flipping_pages = True473 flipping_page_counter = 0474 MAX_FLIPS = 20475 start_time = time()476 while flipping_pages and flipping_page_counter < MAX_FLIPS and time() - start_time < APPLY_TIMEOUT:477 sleep(4 + random())478 # Resume upload might be optional, still need to upload it479 try:480 try:481 resume_ele = driver.find_element(By.XPATH, "//div[@data-automation-id='resumeSection']")482 except:483 resume_ele = driver.find_element(By.XPATH, "//div[@data-automation-id='quickApplyUpload']")484 try:485 resume_ele.find_element(By.XPATH, ".//div[@data-automation-id='file-upload-item']")486 except:487 select_file = resume_ele.find_element(By.XPATH,488 ".//input[@data-automation-id='file-upload-input-ref']")489 select_file.send_keys(RESUME_PATH)490 sleep(5 + random())491 except:492 print("Issue uploading resume")493 # Use resume for all any required uploads, assuming they dont already have an item494 try:495 print("trying to find file upload zones")496 file_upload_drop_zones = driver.find_elements(By.XPATH,497 "//div[@data-automation-id='file-upload-drop-zone']")498 print("file upload zones:", file_upload_drop_zones)499 for zone in file_upload_drop_zones:500 file_already_exists = True501 try:502 # check if an item already exists503 try:504 entire_item = zone.find_element(By.XPATH,505 ".//ancestor::div[starts-with(@data-automation-id, 'formField-')]")506 entire_item.find_element(By.XPATH, ".//div[@data-automation-id='file-upload-item']")507 except Exception as e:508 print(e, "issue at finding upload item")509 file_already_exists = False510 if not file_already_exists:511 # label contains attribute required if it is required512 upload_button = zone.find_element(By.XPATH, ".//button")513 label_id = upload_button.get_attribute('id')514 the_label = driver.find_element(By.XPATH,515 ".//label[@for='" + label_id + "' and @required]")516 print(the_label)517 select_file = zone.find_element(By.XPATH,518 ".//input[@data-automation-id='file-upload-input-ref']")519 select_file.send_keys(RESUME_PATH)520 sleep(5 + random())521 except:522 print("couldnt find required for the file upload")523 except Exception as e:524 print("select file issue")525 solve_questions(driver)526 solve_questions(driver) # necessary because some dropdowns clear required fields527 try:528 sleep(4 + random())529 continue_button = driver.find_element(By.XPATH,530 "//button[@data-automation-id='bottom-navigation-next-button']")531 if "submit" in continue_button.text.lower():532 applied = True533 flipping_pages = False534 continue_button.click()535 sleep(4 + random())536 except:537 print("Couldn't find continue button")538 # need to check if it is submitted539 try:540 driver.find_element(By.XPATH, "//div[@data-automation-id='auth_form_img_container']")541 applied = True542 flipping_pages = False543 except:544 print("Couldn't find congratulations checkmark")545 flipping_pages = False546 flipping_page_counter += 1547 print("\n\nPAGE:\n\n")548 except Exception as e:549 print(e, "base apply")550 return applied551driver = webdriver.Chrome()552driver.get(sys.argv[1])553sleep(4 + random())554if apply(driver):555 print("WORKDAY: APPLIED")556 driver.close()557else:558 print("WORKDAY: ERROR APPLYING")559 driver.close()...

Full Screen

Full Screen

indeed_apply.py

Source:indeed_apply.py Github

copy

Full Screen

1from random import random2from time import sleep, time3from selenium.webdriver.common.by import By4from selenium.webdriver.support.ui import Select5from datetime import date, timedelta6from keyword_config import get_response7from process_label_text import process_label_text8from driver_config import APPLY_TIMEOUT, INCLUDE_OPTIONAL_ANSWERS9QUESTION_TEXT_XPATH_STR = ".//span[starts-with(@class, 'fs-unmask')]"10def derive_input_type(item):11 THE_TYPE = ""12 focus_element = None13 button_group = None14 try:15 focus_element = item.find_element(By.XPATH, ".//fieldset[starts-with(@id, 'input-')]")16 button_group = focus_element.find_elements(By.XPATH, ".//input[starts-with(@id, 'input-')]")17 THE_TYPE = "RADIO"18 except:19 print("error finding radiogroup")20 try:21 focus_element = item.find_element(By.XPATH, ".//fieldset[starts-with(@class, 'ia-MultiselectQuestion')]")22 button_group = focus_element.find_elements(By.XPATH, ".//input[starts-with(@id, 'ifl-CheckboxFormField')]")23 THE_TYPE = "CHECKBOX"24 except:25 print("error finding checkboxes")26 try:27 focus_element = item.find_element(By.XPATH, ".//textarea[starts-with(@id, 'input-')]")28 THE_TYPE = "TEXTAREA"29 except:30 print("error finding textarea")31 try:32 focus_element = item.find_element(By.XPATH, ".//select[starts-with(@id, 'input-')]")33 select = Select(focus_element)34 button_group = select.options35 THE_TYPE = "DROPDOWN"36 except:37 print("error finding dropdown")38 try:39 focus_element = item.find_element(By.XPATH, ".//input[starts-with(@id, 'input-')]")40 if focus_element.get_attribute('type') == "date":41 THE_TYPE = "DATE"42 elif focus_element.get_attribute('type') == "text" or focus_element.get_attribute('type') == "number" or focus_element.get_attribute('type') == "tel":43 THE_TYPE = "TEXT"44 else:45 raise Exception("error finding text, number, or date")46 except:47 print("error finding text, number, or date")48 return [focus_element, button_group, THE_TYPE]49def get_input_field_values(FOCUS_ELEMENT, BUTTON_GROUP, INPUT_TYPE):50 ret_list = []51 if INPUT_TYPE == "RADIO" or INPUT_TYPE == "CHECKBOX":52 id_text_list = []53 for button in BUTTON_GROUP:54 if button.is_selected():55 id_text_list.append(button.get_attribute('id'))56 # translate radio button ids into label text57 for button_id_text in id_text_list:58 ret_list.append(FOCUS_ELEMENT.find_element(By.XPATH, ".//label[@for='" + button_id_text + "']").text)59 elif INPUT_TYPE == "TEXTAREA":60 some_str = FOCUS_ELEMENT.text61 if some_str.replace(' ', '').replace('\n', '') != '':62 ret_list.append(some_str)63 elif INPUT_TYPE == "DROPDOWN":64 select = Select(FOCUS_ELEMENT)65 if len(select.all_selected_options) > 0:66 # default no value is technically a selected option67 # don't append it if that's selected68 for op in select.all_selected_options:69 if op.text != '' and op.text != ' ':70 ret_list.append(op.text)71 elif INPUT_TYPE == "DATE":72 some_str = FOCUS_ELEMENT.get_attribute('value')73 if some_str != '':74 ret_list.append(some_str)75 elif INPUT_TYPE == "TEXT":76 some_str = FOCUS_ELEMENT.get_attribute('value')77 if some_str.replace(' ', '') != '':78 ret_list.append(some_str)79 else:80 ret_list.append("NOT INITIALIZED, TREATING AS A FINISHED ITEM")81 print("unknown type in get_empty_question_items, USING PLACEHOLDER TO IGNORE")82 return ret_list83def resolve_input(driver, item, response):84 global QUESTION_TEXT_XPATH_STR85 DEFAULT_INPUT = 186 DEFAULT_DATE = date.today() + timedelta(14)87 derived = derive_input_type(item)88 FOCUS_ELEMENT = derived[0]89 BUTTON_GROUP = derived[1]90 if BUTTON_GROUP is not None:91 BUTTON_GROUP = BUTTON_GROUP[::-1]92 INPUT_TYPE = derived[2]93 try:94 question_text = item.find_element(By.XPATH, QUESTION_TEXT_XPATH_STR).text95 print("question_text:", question_text, "resovle_input given RESPONSE:", response)96 if INPUT_TYPE == "RADIO":97 clicked_a_button = False98 # try to find exact match99 for button in BUTTON_GROUP:100 # button does not contain text, but only the id101 button_id_text = button.get_attribute('id')102 answer_text = FOCUS_ELEMENT.find_element(By.XPATH, ".//label[@for='" + button_id_text + "']").text103 if response is not None and response.lower() == answer_text.lower():104 driver.execute_script("arguments[0].click();", button)105 clicked_a_button = True106 break107 if not clicked_a_button:108 for button in BUTTON_GROUP:109 print(button.text)110 # button does not contain text, but only the id111 button_id_text = button.get_attribute('id')112 answer_text = FOCUS_ELEMENT.find_element(By.XPATH, ".//label[@for='" + button_id_text + "']").text113 print("ANSWER ITEM:", button_id_text, "ANSWER TEXT:", answer_text)114 print("RESPONSE:", response)115 if response is not None and response in answer_text:116 driver.execute_script("arguments[0].click();", button)117 clicked_a_button = True118 break119 else:120 processed_text = process_label_text(answer_text)121 processed_text_list = processed_text.lower().split()122 response = get_response(processed_text, processed_text_list, INDEXING="DICTIONARY")123 if response is not None:124 driver.execute_script("arguments[0].click();", button)125 clicked_a_button = True126 break127 if not clicked_a_button:128 for button in BUTTON_GROUP:129 print(button.text)130 # button does not contain text, but only the id131 button_id_text = button.get_attribute('id')132 answer_text = FOCUS_ELEMENT.find_element(By.XPATH, ".//label[@for='" + button_id_text + "']").text133 if not clicked_a_button:134 driver.execute_script("arguments[0].click();", BUTTON_GROUP[0])135 elif INPUT_TYPE == "CHECKBOX":136 clicked_a_button = False137 for button in BUTTON_GROUP:138 print(button.text)139 # button does not contain text, but only the id140 button_id_text = button.get_attribute('id')141 answer_text = FOCUS_ELEMENT.find_element(By.XPATH, ".//label[@for='" + button_id_text + "']").text142 print("ANSWER ITEM:", button_id_text, "ANSWER TEXT:", answer_text)143 print("RESPONSE:", response)144 # checkboxes should rely on dictionary indexing only145 if clicked_a_button:146 response = None147 if response is not None and response in answer_text:148 driver.execute_script("arguments[0].click();", button)149 clicked_a_button = True150 else:151 processed_text = process_label_text(answer_text)152 processed_text_list = processed_text.lower().split()153 response = get_response(processed_text, processed_text_list, INDEXING="DICTIONARY")154 if response is not None:155 sleep(1 + random())156 driver.execute_script("arguments[0].click();", button)157 clicked_a_button = True158 if not clicked_a_button:159 driver.execute_script("arguments[0].click();", BUTTON_GROUP[0])160 elif INPUT_TYPE == "TEXTAREA":161 if response is not None:162 FOCUS_ELEMENT.send_keys(response)163 else:164 FOCUS_ELEMENT.send_keys(DEFAULT_INPUT)165 elif INPUT_TYPE == "DROPDOWN":166 options = BUTTON_GROUP167 try:168 if response is not None:169 made_selection = False170 # attempt to find exact match171 for op in options:172 print(response, op.text)173 if response.lower() == op.text.lower():174 print("clicking:", op.text.lower())175 op.click()176 made_selection = True177 break178 if not made_selection:179 for op in options:180 print(response, op.text)181 if response.lower() in op.text.lower():182 print("clicking:", op.text.lower())183 op.click()184 made_selection = True185 break186 if not made_selection:187 options[0].click()188 else:189 options[0].click()190 except Exception as e:191 print(e, "error at trying to select in dropdown")192 elif INPUT_TYPE == "DATE":193 driver.execute_script("arguments[0].click();", FOCUS_ELEMENT)194 FOCUS_ELEMENT.send_keys(DEFAULT_DATE.strftime("%m"))195 sleep(.1)196 FOCUS_ELEMENT.send_keys(DEFAULT_DATE.strftime("%d"))197 sleep(.1)198 FOCUS_ELEMENT.send_keys(DEFAULT_DATE.strftime("%Y"))199 # driver.execute_script("arguments[0].value = arguments[1];", FOCUS_ELEMENT, DEFAULT_DATE)200 elif INPUT_TYPE == "TEXT":201 if response is not None:202 FOCUS_ELEMENT.send_keys(response)203 else:204 FOCUS_ELEMENT.send_keys(DEFAULT_INPUT)205 else:206 print("unknown input type or blank")207 except Exception as e:208 print(e, "error resolving input")209def solve_items(driver, the_items):210 global QUESTION_TEXT_XPATH_STR211 for item in the_items:212 sleep(2 + random())213 question_text = item.find_element(By.XPATH, QUESTION_TEXT_XPATH_STR).text214 processed_text = process_label_text(question_text)215 if "(optional)" in processed_text and not INCLUDE_OPTIONAL_ANSWERS:216 continue217 question_text_list = processed_text.lower().split()218 response = get_response(question_text, question_text_list, INDEXING="TEXT")219 # need to figure out how to differentiate inputs220 resolve_input(driver, item, response)221def get_empty_question_items(question_items):222 empty_question_items = []223 for item in question_items:224 try:225 derived = derive_input_type(item)226 FOCUS_ELEMENT = derived[0]227 BUTTON_GROUP = derived[1]228 INPUT_TYPE = derived[2]229 # questions without an answer list will return [] which is getting appended230 # using placeholder in get_input_field_values to ignore questions without an answer list231 if len(get_input_field_values(FOCUS_ELEMENT, BUTTON_GROUP, INPUT_TYPE)) == 0:232 empty_question_items.append(item)233 except Exception as e:234 print(e, "error get_empty_question_items item")235 return empty_question_items236def solve_questions(driver):237 sleep(2 + random())238 # gather all question items ia-Questions-item239 try:240 base_question_items = driver.find_elements(By.XPATH, "//div[starts-with(@class, 'ia-Questions-item')]")241 empty_question_items = get_empty_question_items(base_question_items)242 solve_items(driver, empty_question_items)243 except Exception as e:244 print(e, "error at aria-invalid")245def apply(driver, job_post):246 # wait until apply button appears247 sleep(6 + random())248 success_applying = False249 try:250 try:251 apply_button = driver.find_element(By.XPATH, ".//div[@id='jobsearch-ViewJobButtons-container']")252 except Exception as e:253 print(e, "apply button")254 sleep(4 + random())255 # try to identify onsite/offsite256 try:257 indeed_button = apply_button.find_element(By.XPATH, ".//*[contains(@class, 'IndeedApplyButton')]")258 if indeed_button.text == "Applied":259 job_post.onsite = True260 return False261 except Exception as e:262 print(e, "not indeed button")263 job_post.onsite = False264 try:265 job_post.href = apply_button.find_element(By.XPATH,266 ".//a[starts-with(@href, 'https://www.indeed.com/applystart')]").get_attribute(267 'href')268 driver.get(job_post.href)269 print(driver.current_url)270 sleep(10 + random())271 print(driver.current_url)272 job_post.href = driver.current_url273 if "indeed" in driver.current_url:274 job_post.onsite = True275 job_post.href = ""276 except Exception as e:277 job_post.onsite = True # so that it is not appended to offline links278 job_post.href = ""279 print(e, "couldn't find offsite href")280 print(job_post)281 if job_post.onsite:282 try:283 indeed_button.click()284 sleep(4 + random())285 except Exception as e:286 print(e, "clicked indeed apply button error")287 flipping_pages = True288 flipping_page_counter = 0289 MAX_FLIPS = 20290 start_time = time()291 while flipping_pages and flipping_page_counter < MAX_FLIPS and time() - start_time < APPLY_TIMEOUT:292 sleep(4 + random())293 solve_questions(driver)294 solve_questions(driver) # necessary because some dropdowns clear required fields295 try:296 sleep(4 + random())297 continue_button = driver.find_element(By.XPATH,298 "//button[starts-with(@class, 'ia-continueButton')]")299 driver.execute_script("arguments[0].click();", continue_button)300 if continue_button.text.lower() == "submit your application":301 success_applying = True302 flipping_pages = False303 except Exception as e:304 print(e, "couldn't find continue button")305 flipping_pages = False306 flipping_page_counter += 1307 else:308 print("criteria not met: job_post onsite:", job_post.onsite)309 except Exception as e:310 print(e, "base apply")...

Full Screen

Full Screen

selection_sort.py

Source:selection_sort.py Github

copy

Full Screen

1'''2task:3Implement the selection sort algorithm4Selection sort works by selecting a start-index, starting with the first and incrementing by one for each iteration. We are not iterating the start-index,5it stays the same during an iteration, increasing by one in-between iterations. This start-index is the same as our swap-index at the beginning of each iteration.6During the iteration, we move from the initial swap-index to the very end of the array, comparing the current swap-index to each index until the end. If during a comparison 7the newly hit index element is smaller than the current swap index, the element at the new index becomes the swap-index for that8iteration. Once the iteration is complete, we swap the start-index with the swap-index (if they are different).9'''10array = [8, 5, 2, 9, 5, 6, 3]11def selection_sort(array):12 focus_element = 013 length = len(array)14 while(focus_element < length - 1):15 smallest_index = focus_element16 for i in range(focus_element + 1, length):17 if(array[smallest_index] > array[i]):18 smallest_index = i19 array[focus_element], array[smallest_index] = array[smallest_index], array[focus_element]20 focus_element += 1 21 return array...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run toolium automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful