def select_version_by_index(self, index): ''' Select the version of the application you want to report on ''' version_dropdown = self.find_element(*self._all_versions_locator) select = Select(version_dropdown) select.select_by_index(index)
class EditBulkCSVFile(BasePageCMS): def __init__(self, driver, wait): self.driver = driver self.wait = wait self.contentProject = Select(self.wait.until(lambda driver : driver.find_element_by_id("id_content_project"))) self.sourceFile = self.wait.until(lambda driver : driver.find_element_by_id("id_file")) self.uploadStatus = self.wait.until(lambda driver : driver.find_element_by_xpath("//div/label[text()='Bulk upload status:']/../p")) def selectContentProjectByIndex(self, index): self.contentProject.select_by_index(index) def typeSourceFile(self, filePath): self.sourceFile.send_keys(filePath) def clickSaveAndContinueEditingButton(self): self.clickSaveAndContinueEditing() return EditBulkCSVFile(self.driver, self.wait) def clickImportItButton(self): self.clickOnLink("Import it") return EditBulkCSVFile(self.driver, self.wait) def getContentProject(self): return self.contentProject.first_selected_option.text def getCurrentSourceFile(self): currentFile = self.wait.until(lambda driver : driver.find_element_by_xpath("//div/label[text()='Source file:']/../p/a")) return currentFile.text def getUploadStatus(self): return self.uploadStatus.text
def test_add_lost_pet(self): self.login() self.assertIn('Cadastrar Pet', self.browser.page_source) self.browser.get(self.live_server_url + '/pets/new/') name = self.browser.find_element_by_name('name') name.send_keys('Test') description = self.browser.find_element_by_name('description') description.send_keys('Testing') kind = self.browser.find_element_by_name('kind') kind = Select(kind) kind.select_by_index(1) self.select_dropdown('city', 1) profile_picture = self.browser.find_element_by_name('profile_picture') profile_picture.send_keys('{}/img/{}.jpg'.format(settings.STATICFILES_DIRS[0], 'sapa')) submit = self.browser.find_element_by_name('submit') submit.click() self.assertIn('Testing', self.browser.page_source) self.assertInHTML('<h2>Test - Desaparecido</h2>', self.browser.page_source)
def test_check_job_details_page(self): driver=self.driver self.mine_job() job_id=self.submit_job() self.assertTrue(self.wait_job_end(job_id)) self.open_job_page(job_id) recipeset_id=self.get_recipe_set_id_from_openning_job_page() recipe_id=self.get_recipe_id_from_openning_job_page() driver.find_element_by_xpath("//a[@class='btn results-tab']").click() driver.find_element_by_xpath("//a[@class='btn hide-results-tab']").click() driver.find_element_by_xpath("//button[@class='btn']").click() driver.find_element_by_xpath("//button[@class='btn']").click() #update whiteboard driver.find_element_by_xpath("//a[@class='list']").click() driver.find_element_by_id("whiteboard").send_keys("Automation-test") driver.find_element_by_xpath("//button[@type='submit']").click() #update Rentention Tag driver.refresh() table=WebDriverSelect(driver.find_element_by_id("job_retentiontag")) table.select_by_index(7) element = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='ui-dialog-buttonset']/button[1]"))) element.click() driver.refresh() table=WebDriverSelect(driver.find_element_by_id("job_retentiontag")) table.select_by_index(2) element = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='ui-dialog-buttonset']/button[1]"))) element.click() #Check kickstart is avaiable driver.refresh() driver.find_element_by_xpath("//a[contains(@href,'kickstart')]").click() self.assertIn("%post",driver.page_source)
def add_new_user(self): add_user_btn = self.browser.find_element_by_id('new-user-btn') add_user_btn.click() self.wait_for_element_with_id('first_name', timeout=10) popup = self.browser.find_element_by_class_name('popup-wrap') first_name_field = popup.find_element_by_id('first_name') last_name_field = popup.find_element_by_id('last_name') other_name_field = popup.find_element_by_id('other_name') phone_field = popup.find_element_by_id('phone') website_field = popup.find_element_by_id('website') department_field = popup.find_element_by_id('department') email_field = popup.find_element_by_id('email') password_field = popup.find_element_by_id('password') confirm_password_field = popup.find_element_by_id('confirm_password') submit_user_field = popup.find_element_by_id('submit-user') gender_ddl = Select(popup.find_element_by_id('gender')) first_name_field.send_keys('blaise') last_name_field.send_keys('pascal') other_name_field.send_keys('adam') phone_field.send_keys('+234578362728') department_field.send_keys('Computing Network Team') website_field.send_keys('www.google.com') email_field.send_keys('*****@*****.**') password_field.send_keys('pass1') confirm_password_field.send_keys('pass1') gender_ddl.select_by_index(1) submit_user_field.click() return {'email': '*****@*****.**', 'name': 'pascal, blaise adam', 'phone': '+234578362728', 'department': 'Computing Network Team'}
def edit_user(self): edit_user_btn = self.browser.find_element_by_css_selector('.btn.btn-primary') edit_user_btn.click() popup = self.browser.find_element_by_class_name('popup-wrap') first_name_field = popup.find_element_by_id('first_name') last_name_field = popup.find_element_by_id('last_name') other_name_field = popup.find_element_by_id('other_name') phone_field = popup.find_element_by_id('phone') department_field = popup.find_element_by_id('department') submit_user_field = popup.find_element_by_id('submit-user') gender_ddl = Select(popup.find_element_by_id('gender')) first_name_field.clear() first_name_field.send_keys('Clement') last_name_field.clear() last_name_field.send_keys('Edith') other_name_field.clear() other_name_field.send_keys('adam') phone_field.clear() phone_field.send_keys('09000675457') department_field.clear() department_field.send_keys('Machine Learning') gender_ddl.select_by_index(2) submit_user_field.click() return {'name': 'edith, clement adam', 'phone': '09000675457', 'department': 'Machine Learning'}
def downloadChunk( link, browser, rFrom, rTo, i ): try : close = browser.find_element_by_xpath("//a[@class='quickoutput-cancel-action']") #close previous download box close.click() except : pass fFrom = str(rFrom) rTo = str(rTo) browser.execute_script("window.scrollTo(0, 0);") #time.sleep(1) browser.find_element_by_xpath("//div[@id='s2id_saveToMenu']//b").click() #save to arrow if i == 1: browser.find_element_by_id('select2-result-label-12').click() #save to other formats else : browser.find_element_by_id('select2-chosen-1').click() #save to other formats browser.find_element_by_id('numberOfRecordsRange').click() #select records range browser.find_element_by_id('markFrom').click() #click on from box browser.find_element_by_id('markFrom').send_keys(fFrom) #enter keys in from box browser.find_element_by_id('markTo').click() #click on to box browser.find_element_by_id('markTo').send_keys(rTo) #enter keys in to box dropdown = browser.find_element_by_id('bib_fields') #find fields dropdown select_box = Select(dropdown) select_box.select_by_index(3) #select option 3 (all records and refs) browser.find_element_by_xpath("//span[@class='quickoutput-action']").click() #click send
def create_new_system(self,fqdn): driver=self.driver driver.get(self.hub_url) simple_search=driver.find_element_by_xpath("//input[@class='search-query']") simple_search.send_keys(fqdn) simple_search.send_keys(Keys.RETURN) if "Items found: 0" in driver.page_source : driver.find_element_by_xpath("//a[@class='btn btn-primary']").click() driver.find_element_by_xpath("//input[@id='form_fqdn']").send_keys(fqdn) lab=WebDriverSelect(driver.find_element_by_id("form_lab_controller_id")) lab.select_by_index(1) Type=WebDriverSelect(driver.find_element_by_id("form_type")) Type.select_by_value("Machine") Status=WebDriverSelect(driver.find_element_by_id("form_status")) Status.select_by_value("Automated") driver.find_element_by_xpath("//a[@class='btn btn-primary']").click() else: driver.get(self.hub_url+"view/"+fqdn) driver.find_element_by_xpath("//a[@class='btn']").click() Type=WebDriverSelect(driver.find_element_by_id("form_status")) Type.select_by_value("Automated") driver.find_element_by_xpath("//a[@class='btn btn-primary']").click() #set power type driver.get(self.hub_url+"view/"+fqdn+"#power") time.sleep(10) Power_type=WebDriverSelect(driver.find_element_by_id("power_power_type_id")) Power_type.select_by_index(1) driver.find_element_by_xpath("//div[@id='power']//button[@class='btn btn-primary']").click
def DG_db(self,index): WebDriverWait(self.driver, 10)\ .until(expected_conditions.visibility_of_element_located,((By.XPATH,".//*[@id='ctl00_ctl00_MasterPageContent_cpv_cqiDatabaseDropDownList']"))) DGDB_DDL = Select(self.driver.find_element(*DG_Details.DG_DB)) print(len(DGDB_DDL.options)) DGDB_DDL.select_by_index(index) sleep(3) self.driver.implicitly_wait(10)
def update_select(el, value, by_text=False): select = Select(el) if value == '': select.select_by_index(0) elif by_text: select.select_by_visible_text(value) else: select.select_by_value(value)
def selectDeleteAction(self): try: action = Select(WebDriverWait(self.driver, 5).until(lambda driver:driver.find_element_by_name("action"))) except: action = Select(WebDriverWait(self.driver, 5).until(lambda driver:driver.find_element_by_name("user_action_select"))) action.select_by_index(1) goButton = self.wait.until(lambda driver:driver.find_element_by_xpath("//button[text()='Go']")) goButton.submit() return DeletePageCMS(self.driver, self.wait)
def test_top_sort_results(self): self._get_page("http://www.imdb.com/chart/top") select = Select(self.driver.find_element_by_name("sort")) sort_options = select.options for option in sort_options: select.select_by_index(sort_options.index(option)) self._assert_search_result()
def DG_DetailsPopup(self, name, desc, index): self.driver.find_element(*DG_Create.DG_Name).send_keys(name) sleep(3) self.driver.find_element(*DG_Create.DG_Description).send_keys(desc) DGDB_DDL = Select(self.driver.find_element(*DG_Create.DG_DB)) print(len(DGDB_DDL.options)) DGDB_DDL.select_by_index(index) sleep(3) self.driver.implicitly_wait(10)
def dropdown_select_by_index(dropdown_web_elem, index): """ :param dropdown_web_elem: select web element :param text: index of row :return: """ case_value = Select(dropdown_web_elem) case_value.select_by_index(index)
def add_course_run(self): self.wait_for_element_visibility('button.js-add-course-run', 'add course run button visible') self.q(css='button.js-add-course-run').first.click() self.wait_for_element_visibility( 'select.js-course-run-select option[value*=\'course\']', 'select course options visible') select = Select(self.browser.find_element_by_css_selector('select.js-course-run-select')) select.select_by_index(1) self.wait_for_element_visibility('button.js-remove-run', 'remove course run button visible')
def selectItemByIndex(self, xPathPath, itemIndex, isBug = False): try: item = self.getElementByXPath(xPathPath, isBug) if item != None: select = Select(item) select.select_by_index(itemIndex) else: logWarning("Cannot select item index '" + str(itemIndex) + "' in dropdown list with XPath: '" + str(xPathPath) + "'") except Exception, e: logWarning(str(e))
def select_option_by_index_from_dropdown(self, element, index): self.wait_for_visible(element) element = self.find_element(element) select = Select(element) self._safe_log(u"Selecting by index '%s' from '%s'", index, self._to_string(element)) select.select_by_index(index)
def create_new_partner(self, **kwargs): self.clear_send_keys('name', kwargs) self.clear_send_keys('star_name', kwargs) self.clear_send_keys('star_email', kwargs) # self.logo_file.send_keys(get_full_path(kwargs['partner_logo'])) partner_status_select = Select(self.partner_status) partner_status_select.select_by_index(kwargs['status']) self.update.click() wait = WebDriverWait(self._driver, 30) wait.until(lambda x: 'Updated successfully.' in self.succes_message.text) self.wait_for_loading()
def select_option(self, value=None, text=None, index=None): # Python3 filter -> list(filter) if len(list(filter(None, (value, text, index)))) != 1: raise ValueError("You must supply exactly one of (value, text, index) kwargs") select = Select(self) if value is not None: select.select_by_value(value) elif text is not None: select.select_by_visible_text(text) else: select.select_by_index(index)
def append(self, item): s = WebDriverSelect(self.driver.find_element_by_locator(self.locator)) method = item[:item.find("=")] value = item[item.find("=") + 1:] if method == "value": s.select_by_value(value) elif method == "index": s.select_by_index(value) elif method == "text": s.select_by_visible_text(value) else: raise saunter.exceptions.InvalidLocatorString("%s is an invalid locator" % item)
def selected(self, val): s = WebDriverSelect(self.driver.find_element_by_locator(self.locator)) method = val[:val.find("=")] value = val[val.find("=") + 1:] if method == "value": s.select_by_value(value) elif method == "index": s.select_by_index(value) elif method == "text": s.select_by_visible_text(value) else: raise saunter.exceptions.InvalidLocatorString(val)
def search_subject(index): driver.switch_to_frame(driver.find_element(By.XPATH,'//iframe[@name="TargetContent"]')) time.sleep(10) select = Select(driver.find_element(By.XPATH,'//div[@id="win0divSSR_CLSRCH_WRK_SUBJECT_SRCH$0"]/select')) select.select_by_index(index) driver.find_element(By.XPATH,'//a[@name="CLASS_SRCH_WRK2_SSR_PB_CLASS_SRCH"]').click() time.sleep(10) try: if driver.find_element(By.XPATH,'//span[@class="SSSMSGWARNINGTEXT"]'): return -1 except Exception,e: pass
def test_create_meas_item_noname(admin_client, live_server, webdriver): selenium = webdriver() try: Product.objects.create(product_name='product1') selenium.get(live_server + '/measurement_item/new/') login_as_admin(selenium) serial_nr = selenium.find_element_by_id('id_serial_nr') serial_nr.send_keys('test_serial_nr') product = Select(selenium.find_element_by_id('id_product')) product.select_by_index(1) selenium.find_element_by_tag_name('form').submit() assert selenium.current_url == live_server + '/' assert len(MeasurementItem.objects.all()) == 1 finally: selenium.quit()
def callCompleteNotes(driver): driver.find_element_by_xpath("//*[@id='sp-completevisit']/div/div[2]/div/div[3]/textarea").send_keys( "This is an Automation Test!" ) driver.find_element_by_xpath("//*[@id='sp-completevisit']/div/div[2]/div/div[4]/span/span/input").send_keys( "Automation objective" ) contactMade = Select( driver.find_element_by_xpath("//*[@id='sp-completevisit']/div/div[2]/div/div[5]/div[1]/select") ) contactMade.select_by_index(1) productiveVisit = Select( driver.find_element_by_xpath("//*[@id='sp-completevisit']/div/div[2]/div/div[5]/div[2]/select") ) productiveVisit.select_by_index(1) driver.find_element_by_xpath("//*[@id='CompleteVisit']/div[2]/button[1]").click()
class EditFeatureWellPageCMS(BasePageCMS): def __init__(self, driver, wait): self.driver = driver self.wait = wait self.lmSite = Select(self.wait.until(lambda driver : driver.find_element_by_id("id_lmsite"))) self.title = self.wait.until(lambda driver : driver.find_element_by_id("id_title")) self.items = self.wait.until(lambda driver : driver.find_elements_by_xpath("//select[contains(@id,'id_orderedfeaturewellitem_set')]/option[@selected='selected' and not(text()='---------')]")) self.comboboxForNewItem = Select(self.wait.until(lambda driver : driver.find_element_by_xpath("//select[contains(@id,'id_orderedfeaturewellitem_set')]/option[@selected='selected' and text()='---------']/.."))) def getAttachedFeatureWellItems(self): itemsText = [] for item in self.items: itemsText.append(item.text) return itemsText def selectNewItemByIndex(self, index): self.comboboxForNewItem.select_by_index(index) def clickSaveAndContinueEditingButton(self): self.clickSaveAndContinueEditing() return EditFeatureWellPageCMS(self.driver, self.wait)
class AddRequiredAttribution(BasePageCMS): def __init__(self, driver, wait): self.driver = driver self.wait = wait self.entityBox = Select(self.wait.until(lambda driver :driver.find_element_by_id("id_entity"))) self.roleBox = Select(self.wait.until(lambda driver :driver.find_element_by_id("id_role"))) self.requiredAttributionTextArea = self.wait.until(lambda driver :driver.find_element_by_xpath(".//*[@id='id_text']")) def selectEntity(self): self.entityBox.select_by_index(2) def selectRole(self, role): self.roleBox.select_by_visible_text(role) def writeInTextArea(self, requiredAttributionText): self.requiredAttributionTextArea.send_keys(requiredAttributionText) def clickToSaveAndContinue(self): self.clickSaveAndContinueEditing() return AddRequiredAttribution(self.driver, self.wait) def getSelectedEntity(self): return self.entityBox.first_selected_option.text def getSelectedRole(self): return self.roleBox.first_selected_option.text
class ResourceReportCMS(ReportsBaseCMS): def __init__(self, driver, wait, report=None): self.driver = driver self.wait = wait if(report == None): self.driver.get(ServerRelated().serverToBeTested() + "admin/reports/resource-report/") self.typeFilter = Select(self.wait.until(lambda driver : driver.find_element_by_id("id_type"))) self.contentProjFilter = Select(self.wait.until(lambda driver : driver.find_element_by_id("id_content_project__title"))) def selectType(self, option): self.typeFilter.select_by_visible_text(option) def selectContentProject(self, index): self.contentProjFilter.select_by_index(index) def clickGetResultsButton(self): self.clickGetResults() return ResourceReportCMS(self.driver, self.wait, "report") def clickPdfButton(self): self.clickPdf() return ResourceReportCMS(self.driver, self.wait, "report")
class EditAddMediaPageCMS(BasePageCMS): def __init__(self, driver, wait): self.driver = driver self.wait = wait self.nameField = self.wait.until(lambda driver : driver.find_element_by_id("id_name")) self.contentProject = Select(self.wait.until(lambda driver : driver.find_element_by_id("id_content_project"))) self.file = self.wait.until(lambda driver : driver.find_element_by_id("id_file")) def getName(self): return self.nameField.get_attribute("value") def getSelectedContentProject(self): return self.contentProject.first_selected_option.text def typeName(self, name): self.nameField.clear() self.nameField.send_keys(name) def typeFilePath(self, filePath): self.file.send_keys(filePath) def selectContentProjectByVisibleText(self, text): self.contentProject.select_by_visible_text(text) def selectContentProjectByIndex(self, index): self.contentProject.select_by_index(index) def clickSaveButton(self): self.clickSave() return MediasPageCMS(self.driver, self.wait) def getCurrentMediaFile(self): self.currentMediaFile = self.wait.until(lambda driver : driver.find_element_by_xpath("//div[@class='form-row file']/div/a")) return self.currentMediaFile.text
#driver = webdriver.Firefox(firefox_options=self.options); #options.headless = True #driver=webdriver.Firefox(options=options) #driver = webdriver.Firefox(executable_path='/MachintoshHD/Users/shailysaigal/Downloads/geckodriver') driver.get("https://aisel.aisnet.org/do/search") time.sleep(5) adv=driver.find_element_by_id("switch-to-advanced") adv.click() time.sleep(random.randint(20,30)) nbutton1=driver.find_element_by_xpath("//a[@aria-label='dismiss cookie message']") nbutton1.click() select_fr = Select(driver.find_element_by_id("field_1")) select_fr.select_by_index(1) select_fr = Select(driver.find_element_by_id("results-format")) select_fr.select_by_index(1) search_box = driver.find_element_by_id("value_1") search_box.send_keys("crowdfunding") time.sleep(random.randint(10,15)) search_button = driver.find_element_by_id("do-search-advanced") search_button.click() time.sleep(random.randint(20,40)) driver.close()
def setManagerofvendor(self, value): list = Select( self.driver.find_element_by_xpath(self.drpmgrOfVendor_xpath)) list.select_by_index(value)
def check_download_csv1(self): p = pwd() self.cal = GetData() self.fname = file_extention() self.driver.implicitly_wait(100) self.driver.find_element_by_xpath(Data.hyper_link).click() self.cal.page_loading(self.driver) management_name = self.driver.find_element_by_id('nm').text name = management_name[16:].strip().lower() select_district = Select(self.driver.find_element_by_id('choose_dist')) select_block = Select(self.driver.find_element_by_id('choose_block')) select_cluster = Select( self.driver.find_element_by_id('choose_cluster')) count = 0 for x in range( int(len(select_district.options)) - 1, int(len(select_district.options))): select_district.select_by_index(x) self.cal.page_loading(self.driver) for y in range( len(select_block.options) - 1, len(select_block.options)): select_block.select_by_index(y) self.cal.page_loading(self.driver) for z in range(1, len(select_cluster.options)): select_cluster.select_by_index(z) self.cal.page_loading(self.driver) value = self.driver.find_element_by_id( 'choose_cluster').get_attribute('value') value = value.split(":") nodata = self.driver.find_element_by_id("errMsg").text markers = self.driver.find_elements_by_class_name( Data.dots) if len(markers) - 1 == 0: print(select_cluster.options[z].text, "does not contains markers on map") else: self.driver.find_element_by_id(Data.Download).click() time.sleep(3) self.filename = p.get_download_dir( ) + "/" + self.fname.scmap_clusterwise( ) + name + '_schools_of_cluster_' + value[1].strip( ) + '_' + self.cal.get_current_date() + '.csv' print(self.filename) if not os.path.isfile(self.filename): print(select_cluster.options[z].text, "csv file is not downloaded!") count = count + 1 else: with open(self.filename) as fin: csv_reader = csv.reader(fin) data = list(csv_reader) countrecords = len(data) # header = next(csv_reader) # total = 0 # for row in csv.reader(fin): # total += int(row[2]) school = self.driver.find_element_by_id( "schools").text sc = re.sub('\D', "", school) if int(sc) != int(countrecords) - 1: print(select_block.options[y].text, "schools:", int(countrecords) - 1, int(sc), "mismatch found") count = count + 1 os.remove(self.filename) return count
#国際文化学部を選択 element = driver.find_element_by_css_selector("#menu > li:nth-child(1)") element.click() #移動 element = driver.find_element_by_css_selector("#menu > li.sub.click > ul > li:nth-child(2) > a") element.click() time.sleep(1) #年度(2018年)を選択 element = driver.find_element_by_css_selector("#nendo") indexNum = 7 select = Select(element) #セレクトタグのオプションをインデックス番号から選択する select.select_by_index(indexNum) time.sleep(1) sum_class_info = [] #月曜日 page_source=driver.page_source add_sum_class() #火曜日 element = driver.find_element_by_css_selector("#jikanwariKeywordForm > table > tbody > tr:nth-child(2) > td:nth-child(2) > table > tbody > tr:nth-child(4) > td > table:nth-child(1) > tbody > tr > td > a:nth-child(1)") element.click() time.sleep(1) page_source=driver.page_source
obj.accept() print("Clicked on the OK Button in the Alert Window") time.sleep(2) print("Writing to text area") text_area = driver.find_element_by_id('daText') text_area.send_keys("This text is sent using Python code.") time.sleep(3) print("selecting from dropdown") time.sleep(2) obj = Select(driver.find_element_by_id("daColors")) obj.select_by_index(2) time.sleep(3) print("click on web link to Ponzi's python site") driver.find_element(By.LINK_TEXT, "PonzisPython").click() time.sleep(4) # Closes web page driver.close()
def check_csv_download(self): p = pwd() self.cal = GetData() self.driver.implicitly_wait(60) self.driver.find_element_by_xpath(Data.hyper_link).click() self.cal.page_loading(self.driver) select_district = Select(self.driver.find_element_by_name('myDistrict')) select_block = Select(self.driver.find_element_by_name('myBlock')) select_cluster = Select(self.driver.find_element_by_name('myCluster')) count = 0 for x in range(int(len(select_district.options))-1, int(len(select_district.options))): select_district.select_by_index(x) self.cal.page_loading(self.driver) for y in range(1, len(select_block.options)): select_block.select_by_index(y) self.cal.page_loading(self.driver) for z in range(1, len(select_cluster.options)): select_cluster.select_by_index(z) self.cal.page_loading(self.driver) nodata = self.driver.find_element_by_id("errMsg").text if nodata == "No data found": print(select_district.options[x].text,select_block.options[y].text,select_cluster.options[z].text,"no data found!") count = count + 1 else: self.driver.find_element_by_id(Data.Download).click() time.sleep(3) self.filename = p.get_download_dir() + "/School_level_CRC_Report.csv" if not os.path.isfile(self.filename): print(select_cluster.options[z].text ," csv file not downloaded") else: with open(self.filename) as fin: csv_reader = csv.reader(fin, delimiter=',') header = next(csv_reader) tschools = 0 vsts = 0 vstd = 0 for row in csv.reader(fin): tschools += int(row[0]) vsts += int(row[2]) vstd += int(row[1]) totalschools = self.driver.find_element_by_id("schools").text visited = self.driver.find_element_by_id("visited").text visits = self.driver.find_element_by_id("visits").text tsc = re.sub('\D', "", totalschools) vs = re.sub('\D', "", visits) vd = re.sub('\D', "", visited) if int(tsc) != tschools: print(select_district.options[x].text, ":", "total no of schools :", tschools, int(tsc), "records are mismatch found") count = count + 1 if int(vs) != vsts: print(select_district.options[x].text, ":", "total no of visits :", int(vs), vsts, "records are mismatch found") count = count + 1 if int(vd) != vstd: print(select_district.options[x].text, ":", "total no of visits :", int(vd), vstd, "records are mismatch found") count = count + 1 self.remove_csv1() return count
def select_by_index(self, number): select_option_index = Select(self.driver.find_element(*self.order)) select_option_index.select_by_index(number)
def select_color(self): element = self.selenium.find_element(*self._select_color_locator) select = Select(element) select.select_by_index(1)
def findSelectIndex(driver, id, str): select = Select(findId(driver, id)) select.select_by_index(str) return select
def test_prefer_location(self): prefer_location = driver.find_element_by_xpath( "//select[@name='prefer_location_to_hire']") select = Select(prefer_location) select.select_by_index(0) time.sleep(3)
def getProductsDetailInfo(self, url_list): # 個別ページ情報一覧 product_info_list = [] # ドライバ起動 driver = self.set_driver("chromedriver.exe",False) # ブラウザを開き、URLにアクセス driver.get("https://www.amazon.co.jp/ref=nav_logo") time.sleep(1) # 1件ずつ情報を抽出 for target_info in url_list : name = target_info[0] # 商品名 url = target_info[1] # 商品ページURL stock_info = "" # 在庫情報 delivery_datetime = "" # お届け日時 asin = "" # ASIN,ISBN-13 price = "" # 価格 shipper = "" # 出荷元 distributor = "" # 販売元 # URLを開く driver.get(url) time.sleep(2) # トランザクション開始 try : print("----------------------------------------------------------------------------------------------") print("商品名:" + name) # 服のサイズ選択がある場合に一番小さいサイズを選択する dropdown = driver.find_elements_by_css_selector("#native_dropdown_selected_size_name") if len(dropdown) > 0 : select = Select(dropdown[0]) select.select_by_index(1) time.sleep(2) # 定期おトク便の選択項目がある場合に通常の注文を選択する if len(driver.find_elements_by_css_selector("#buyNew_cbb")) > 0 : driver.find_element_by_id("buyNew_cbb").click() # 在庫情報を取得 stock_info = re.sub("\n","",driver.find_element_by_css_selector("#availability > span").get_attribute("textContent")) print("在庫情報:" + stock_info) # ダウンロード版を除外 if stock_info == "今すぐダウンロードできます。" : raise Exception # ASINまたはISBN-13を取得 if len(driver.find_elements_by_css_selector("#productDetails_detailBullets_sections1 > tbody > tr")) > 0 : reg_info_box = driver.find_elements_by_css_selector("#productDetails_detailBullets_sections1 > tbody > tr") for reg_info in reg_info_box : if "ASIN" in reg_info.find_element_by_tag_name("th").get_attribute("textContent") : asin = re.sub("\n","",reg_info.find_element_by_tag_name("td").get_attribute("textContent")) print("ASIN/ISBN-13:" + asin) break else : reg_info_box = driver.find_elements_by_css_selector("#detailBullets_feature_div > ul > li > span") for reg_info in reg_info_box : if "ASIN" in reg_info.find_element_by_css_selector("span:nth-of-type(1)").get_attribute("textContent") or "ISBN-13" in reg_info.find_element_by_css_selector("span:nth-of-type(1)").get_attribute("textContent"): asin = reg_info.find_element_by_css_selector("span:nth-of-type(2)").get_attribute("textContent") print("ASIN/ISBN-13:" + asin) break # 出品者が複数存在する場合 if stock_info == "出品者からお求めいただけます。" : time.sleep(2) # すべての出品を見るボタンをクリック driver.find_element_by_id("buybox-see-all-buying-choices-announce").click() time.sleep(2) # 新品の出品のみに絞り込み driver.find_element_by_id("aod-filter-string").click() driver.find_element_by_css_selector("#new > div > label > i").click() time.sleep(1) # お届け日時を取得 if len(driver.find_elements_by_css_selector("#ddmDeliveryMessage > b")) > 0 : delivery_datetime = re.sub("\n|^ +","",driver.find_element_by_css_selector("#ddmDeliveryMessage > b").get_attribute("textContent")) elif len(driver.find_elements_by_css_selector("#ddmDeliveryMessage > div > b")) > 0 : delivery_datetime = re.sub("\n|^ +","",driver.find_element_by_css_selector("#ddmDeliveryMessage > div > b").get_attribute("textContent")) elif len(driver.find_elements_by_css_selector("#ddmDeliveryMessage > div > span > b")) > 0 : delivery_datetime = re.sub("\n|^ +","",driver.find_element_by_css_selector("#ddmDeliveryMessage > div > span > b").get_attribute("textContent")) else : pass print("お届け日時:" + delivery_datetime) # 価格を取得 if len(driver.find_elements_by_css_selector("#priceblock_ourprice")) > 0 : price = re.sub("\n|¥","",driver.find_element_by_id("priceblock_ourprice").get_attribute("textContent")) elif len(driver.find_elements_by_css_selector("#price_inside_buybox")) > 0 : price = re.sub("\n|¥","",driver.find_element_by_id("price_inside_buybox").get_attribute("textContent")) elif len(driver.find_elements_by_css_selector("#newBuyBoxPrice")) > 0 : price = re.sub("\n|¥","",driver.find_element_by_id("newBuyBoxPrice").get_attribute("textContent")) elif len(driver.find_elements_by_css_selector("#aod-price-1 > span > span.a-offscreen")) > 0 : price = re.sub("\n|¥","",driver.find_element_by_css_selector("#aod-price-1 > span > span.a-offscreen").get_attribute("textContent")) else : price = re.sub("\n|¥","",driver.find_element_by_css_selector("#tmmSwatches > ul > .selected > span > span > span > a > span:nth-of-type(2) > span:nth-of-type(1)").get_attribute("textContent")) print("価格:" + price) # 出荷元を取得 if len(driver.find_elements_by_css_selector("#tabular-buybox-truncate-0 > span > span")) > 0 : shipper = re.sub("\n","",driver.find_element_by_css_selector("#tabular-buybox-truncate-0 > span > span").get_attribute("textContent")) elif len(driver.find_elements_by_css_selector("#merchant-info > a")) > 0 : shipper = re.sub("\n","",driver.find_element_by_css_selector("#merchant-info > a").get_attribute("textContent")) else : shipper = re.sub("\n","",driver.find_element_by_css_selector("#aod-offer-shipsFrom > div > div > div.a-fixed-left-grid-col.a-col-right > span").get_attribute("textContent")) print("出荷元:" + shipper) # 販売元を取得 if len(driver.find_elements_by_css_selector("#tabular-buybox-truncate-1 > span > span > a")) > 0 : distributor = re.sub("\n","",driver.find_element_by_css_selector("#tabular-buybox-truncate-1 > span > span > a").get_attribute("textContent")) elif len(driver.find_elements_by_css_selector("#merchant-info > a")) > 0 : distributor = re.sub("\n","",driver.find_element_by_css_selector("#merchant-info > a").get_attribute("textContent")) else : distributor = re.sub("\n","",driver.find_element_by_css_selector("#aod-offer-soldBy > div > div > div.a-fixed-left-grid-col.a-col-right > a").get_attribute("textContent")) print("販売元:" + distributor) # 個別ページ情報リストに格納 product_info_list.append([asin, name, price, delivery_datetime, shipper, distributor, url]) except Exception as e: # 除外対象の商品の為、コンソールに情報を出力して処理をスキップ print(e) print("抽出対象外の商品のため処理をスキップしました。 商品名:{0}, URL:{1}".format(name,url)) # ブラウザを閉じる driver.close() # 個別ページ情報リストを返却 return product_info_list
import time from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.select import Select from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC driver = webdriver.Chrome("///home/raghava/Music/chromedriver") driver.get("https://rahulshettyacademy.com/angularpractice/") driver.find_element_by_name("name").send_keys("pavankumar") driver.find_element_by_name("email").send_keys("*****@*****.**") driver.find_element_by_xpath("//input[@type='password']").send_keys("12345678") driver.find_element_by_css_selector("input[type='checkbox']").click() dropdowm = Select(driver.find_element_by_xpath("//select[@id='exampleFormControlSelect1']")) dropdowm.select_by_index(1) driver.find_element_by_xpath("//input[@id='inlineRadio2']").click() driver.find_element_by_xpath("//input[@type='submit']").click() textMatch = driver.find_element_by_css_selector("div[class*='alert-success']").text print(textMatch) assert ("Success!" in textMatch) driver.find_element_by_css_selector("a[href*='shop']").click() cards = driver.find_elements_by_css_selector(".card-title a") i = -1 for card in cards: i = i+1 cardtext = card.text print(cardtext) if cardtext == "Blackberry": driver.find_elements_by_css_selector(".card-footer button")[i].click() driver.find_element_by_css_selector("a[class*='btn-primary']").click() driver.find_element_by_xpath("//button[@class='btn btn-success']").click()
import time from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.select import Select browser = webdriver.Chrome(ChromeDriverManager().install()) browser.get('https://mbasic.facebook.com/') # time.sleep(5) user = "******" password = "******" browser.find_element_by_name("email").send_keys(user) # time.sleep(2) browser.find_element_by_name("pass").send_keys(password) browser.find_element_by_name("login").click() browser.find_element_by_class_name("bl.bm.bn.bo.bp.bq").click() v = Select(browser.find_element_by_name("verification_method")) v.select_by_index(1) browser.find_element_by_class_name("bi.bj.bk.bl.bm.bn").click() date = Select(browser.find_element_by_name("birthday_captcha_day")) date.select_by_index(25) month = Select(browser.find_element_by_name("birthday_captcha_month")) month.select_by_visible_text("Sep") year = Select(browser.find_element_by_name("birthday_captcha_year")) for opt in year.options: year.select_by_visible_text("2001") browser.find_element_by_class_name("bj.bk.bl.bm.bn.bo").click() browser.find_element_by_class_name("bg.bh.bi.bj.bk.bl").click() browser.find_element_by_class_name("bh.bf.bg").click() browser.find_element_by_xpath( "//*[@id=\"m-timeline-cover-section\"]/div[3]/a[2]").click() browser.find_element_by_xpath( "//*[@id=\"root\"]/div[1]/div[2]/div/div[2]/div[1]/table/tbody/tr/td[2]/a"
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.select import Select from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.common.keys import Keys import time driver = webdriver.Chrome(ChromeDriverManager().install()) driver.implicitly_wait(10) driver.maximize_window() driver.get("http://demo.automationtesting.in/Register.html") time.sleep(5) select = Select(driver.find_element_by_id("Skills")) # select.select_by_visible_text("Data Analytics") # time.sleep(5) select.select_by_index(4) time.sleep(5) # select.select_by_value("Desktop Publishing") # time.sleep(5) #count num of options print(len(select.options)) allOptions = select.options for option in allOptions: print(option.text) links = driver.find_elements(By.TAG_NAME, "a") print("number of links", len(links)) for link in links: print(link.text) driver.find_element(By.LINK_TEXT, "More").click() time.sleep(5) driver.close()
def Select_By_Index_From_DropDown(self, locator, int_index): data = self.driver.find_element_by_xpath(locator) sel = Select(data) sel.select_by_index(int_index)
def FieldPopulation(self): # Dropdown the 'Additional Client details' menu self.driver.find_element_by_xpath( '//*[@id="new_client"]/div/div/div/div[1]/div[1]/sg-accordion/sg-accordion-section[2]/sg-accordion-section-header/div/div[2]/div/div' ).click() time.sleep(1.5) # FIELDS TO FILL #Name time.sleep(1.5) self.driver.find_element_by_xpath( '/html/body/div[2]/div[2]/div[2]/div[1]/div[2]/div/form/div/div/div/div[1]/div[1]/div[2]/label/div[1]/div/div/div[1]/div[2]/placeholder-field/input' ).send_keys(name_fn) self.driver.find_element_by_xpath( '/html/body/div[2]/div[2]/div[2]/div[1]/div[2]/div/form/div/div/div/div[1]/div[1]/div[2]/label/div[1]/div/div/div[1]/div[3]/placeholder-field/input' ).send_keys(name_ln) self.driver.find_element_by_xpath( '/html/body/div[2]/div[2]/div[2]/div[1]/div[2]/div/form/div/div/div/div[1]/div[1]/div[2]/label/div[1]/div/div/div[2]/div/placeholder-field/input' ).send_keys(provider) self.driver.find_element_by_xpath( '/html/body/div[2]/div[2]/div[2]/div[1]/div[2]/div/form/div/div/div/div[1]/div[1]/div[2]/div[2]/ul/li/div/div[2]/div/div/div[2]/div/div[1]/placeholder-field/input' ).send_keys(number) self.driver.find_element_by_xpath( '/html/body/div[2]/div[2]/div[2]/div[1]/div[2]/div/form/div/div/div/div[1]/div[1]/div[2]/div[3]/ul/li/div/div[2]/div/div/div[2]/div/div[1]/placeholder-field/input' ).send_keys(billing['Email'].values[0]) #Uncheck 'Billing address is the same...' checkbox self.driver.find_element_by_xpath( '/html/body/div[2]/div[2]/div[2]/div[1]/div[2]/div/form/div/div/div/div[1]/div[2]/div[4]/div/div[1]/label/sg-icon' ).click() time.sleep(1.5) #Address # Dropdown opens - SEND 'ESCAPE' KEY TO EXIT' time.sleep(2) self.driver.find_element_by_xpath( '//*[@id="new_client"]/div/div/div/div[1]/div[2]/div[3]/div[2]/div/div[1]/div/div[1]/div/placeholder-field/input' ).send_keys(street1) self.driver.find_element_by_xpath( '//*[@id="new_client"]/div/div/div/div[1]/div[2]/div[3]/div[2]/div/div[1]/div/div[1]/div/placeholder-field/input' ).send_keys(webdriver.common.keys.Keys.ESCAPE) time.sleep(1.5) #City self.driver.find_element_by_xpath( '/html/body/div[2]/div[2]/div[2]/div[1]/div[2]/div/form/div/div/div/div[1]/div[2]/div[3]/div[2]/div/div[1]/div/div[3]/div[1]/placeholder-field/input' ).send_keys(city) #State self.driver.find_element_by_xpath( '//*[@id="new_client"]/div/div/div/div[1]/div[2]/div[3]/div[2]/div/div[1]/div/div[3]/div[2]/placeholder-field/input' ).send_keys(state) #Postcode self.driver.find_element_by_xpath( '//*[@id="new_client"]/div/div/div/div[1]/div[2]/div[3]/div[2]/div/div[1]/div/div[4]/div[1]/placeholder-field/input' ).send_keys(postcode) #Contact details #driver.find_element_by_xpath('//*[@id="client_phones_attributes_1587200583889_number"]').sendkeys('9844 3360') #Case Manager self.driver.find_element_by_xpath( '/html/body/div[2]/div[2]/div[2]/div[1]/div[2]/div/form/div/div/div/div[1]/div[1]/sg-accordion/sg-accordion-section[2]/sg-accordion-section-body/div[1]/placeholder-field[1]/input' ).send_keys(manager) #Case Manager Contact self.driver.find_element_by_xpath( '/html/body/div[2]/div[2]/div[2]/div[1]/div[2]/div/form/div/div/div/div[1]/div[1]/sg-accordion/sg-accordion-section[2]/sg-accordion-section-body/div[1]/placeholder-field[3]/input' ).send_keys(m_phone) #DOB self.driver.find_element_by_xpath( '/html/body/div[2]/div[2]/div[2]/div[1]/div[2]/div/form/div/div/div/div[1]/div[1]/sg-accordion/sg-accordion-section[2]/sg-accordion-section-body/div[1]/placeholder-field[7]/input' ).send_keys(dob) #Age self.driver.find_element_by_xpath( '/html/body/div[2]/div[2]/div[2]/div[1]/div[2]/div/form/div/div/div/div[1]/div[1]/sg-accordion/sg-accordion-section[2]/sg-accordion-section-body/div[1]/placeholder-field[8]/input' ).send_keys(age) #Home/Mobile self.driver.find_element_by_xpath( '/html/body/div[2]/div[2]/div[2]/div[1]/div[2]/div/form/div/div/div/div[1]/div[1]/sg-accordion/sg-accordion-section[2]/sg-accordion-section-body/div[1]/placeholder-field[9]/input' ).send_keys(number) #Next of Kin self.driver.find_element_by_xpath( '/html/body/div[2]/div[2]/div[2]/div[1]/div[2]/div/form/div/div/div/div[1]/div[1]/sg-accordion/sg-accordion-section[2]/sg-accordion-section-body/div[1]/placeholder-field[10]/input' ).send_keys(nok) #Next of Kin Contact self.driver.find_element_by_xpath( '/html/body/div[2]/div[2]/div[2]/div[1]/div[2]/div/form/div/div/div/div[1]/div[1]/sg-accordion/sg-accordion-section[2]/sg-accordion-section-body/div[1]/placeholder-field[11]/input' ).send_keys(nok_contact) #Availability self.driver.find_element_by_xpath( '/html/body/div[2]/div[2]/div[2]/div[1]/div[2]/div/form/div/div/div/div[1]/div[1]/sg-accordion/sg-accordion-section[2]/sg-accordion-section-body/div[1]/placeholder-field[12]/input' ).send_keys(start) #Medical Notes self.driver.find_element_by_xpath( '/html/body/div[2]/div[2]/div[2]/div[1]/div[2]/div/form/div/div/div/div[1]/div[1]/sg-accordion/sg-accordion-section[2]/sg-accordion-section-body/div[1]/placeholder-field[13]/input' ).send_keys(med_detail) time.sleep(0.5) #Additional Notes self.driver.find_element_by_xpath( '/html/body/div[2]/div[2]/div[2]/div[1]/div[2]/div/form/div/div/div/div[1]/div[1]/sg-accordion/sg-accordion-section[2]/sg-accordion-section-body/div[1]/placeholder-field[14]/input' ).send_keys(overview) #Massage details self.driver.find_element_by_xpath( '/html/body/div[2]/div[2]/div[2]/div[1]/div[2]/div/form/div/div/div/div[1]/div[1]/sg-accordion/sg-accordion-section[2]/sg-accordion-section-body/div[1]/placeholder-field[15]/input' ).send_keys(reason) time.sleep(2) #Enter Billing Details self.driver.find_element_by_xpath( '/html/body/div[2]/div[2]/div[2]/div[1]/div[2]/div/form/div/div/div/div[1]/div[2]/div[4]/div/div[2]/div/div[1]/div/placeholder-field/input' ).send_keys(billing['Billing Street 1'].values[0]) self.driver.find_element_by_xpath( '/html/body/div[2]/div[2]/div[2]/div[1]/div[2]/div/form/div/div/div/div[1]/div[2]/div[4]/div/div[2]/div/div[2]/div/placeholder-field/input' ).send_keys(billing['Billing Street 2'].values[0]) self.driver.find_element_by_xpath( '/html/body/div[2]/div[2]/div[2]/div[1]/div[2]/div/form/div/div/div/div[1]/div[2]/div[4]/div/div[2]/div/div[3]/div[1]/placeholder-field/input' ).send_keys(billing['Billing City'].values[0]) self.driver.find_element_by_xpath( '/html/body/div[2]/div[2]/div[2]/div[1]/div[2]/div/form/div/div/div/div[1]/div[2]/div[4]/div/div[2]/div/div[3]/div[2]/placeholder-field/input' ).send_keys(billing['Billing State'].values[0]) self.driver.find_element_by_xpath( '/html/body/div[2]/div[2]/div[2]/div[1]/div[2]/div/form/div/div/div/div[1]/div[2]/div[4]/div/div[2]/div/div[4]/div[1]/placeholder-field/input' ).send_keys(str(billing['Postcode'].values[0])) #Select Australia from dropdown select_fr = Select( self.driver.find_element_by_xpath( '/html/body/div[2]/div[2]/div[2]/div[1]/div[2]/div/form/div/div/div/div[1]/div[2]/div[4]/div/div[2]/div/div[4]/div[2]/div/select' )) select_fr.select_by_index(0) # CREATE CLIENT self.driver.find_element_by_xpath( '/html/body/div[2]/div[2]/div[2]/div[1]/div[2]/div/form/div/div/div/div[2]/div[2]/div/button[1]' ).click() print('Successfully created client ' + str(name_fn) + str(name_ln) + 'in Jobber') time.sleep(2) ### Need to get past possible 'duplicate' pop up: self.driver.find_element_by_name('commit').click() time.sleep(2.5) ## Add AgedCare Tag self.driver.find_element_by_xpath( '/html/body/div[2]/div[2]/div[2]/div[1]/div[2]/div/div[2]/div[2]/div[1]/div[2]/a' ).click() time.sleep(1.5) self.driver.find_element_by_xpath( '/html/body/div[2]/div[2]/div[2]/div[1]/div[2]/div/div[2]/div[2]/div[2]/form/div/div[1]/placeholder-field/input' ).send_keys('AgedCare') self.driver.find_element_by_xpath( '/html/body/div[2]/div[2]/div[2]/div[1]/div[2]/div/div[2]/div[2]/div[2]/form/div/div[2]/a' ).click() time.sleep(1) self.driver.find_element_by_xpath( '/html/body/div[2]/div[2]/div[2]/div[1]/div[2]/div/div[2]/div[2]/div[2]/form/div/div[1]/placeholder-field/input' ).send_keys('New') self.driver.find_element_by_xpath( '/html/body/div[2]/div[2]/div[2]/div[1]/div[2]/div/div[2]/div[2]/div[2]/form/div/div[2]/a' ).click() print('Added AgedCare & New Tags') time.sleep(1) ## CREATE JOB #Open Dropdown self.driver.find_element_by_xpath( '/html/body/div[2]/div[2]/div[2]/div[1]/div[2]/div/div[1]/div[4]/div[1]/div/div/button' ).click() time.sleep(1) #Select 'job' self.driver.find_element_by_xpath( '/html/body/div[2]/div[2]/div[2]/div[1]/div[2]/div/div[1]/div[4]/div[1]/div/div/div[1]/nav/a[3]' ).click() #Add freq to job title self.driver.find_element_by_xpath( '/html/body/div[2]/div[2]/div[2]/div[1]/div[2]/div/form[1]/div/div/div/div[1]/div/div[2]/div[1]/div[2]/div[1]/div/placeholder-field/input' ).send_keys(freq) #Add notes to job self.driver.find_element_by_xpath( '/html/body/div[2]/div[2]/div[2]/div[1]/div[2]/div/form[1]/div/div[1]/div/div[1]/div/div[2]/div[1]/div[2]/div[2]/div/placeholder-field/textarea' ).send_keys(notes) #Check 'Schedule Later' self.driver.find_element_by_xpath( '/html/body/div[2]/div[2]/div[2]/div[1]/div[2]/div/form[1]/div/div[1]/div/div[2]/div[2]/div[1]/div/div[1]/div/div[2]/div/div[4]/div/label/sg-icon' ).click() #Save Job self.driver.find_element_by_xpath( '/html/body/div[2]/div[2]/div[2]/div[1]/div[2]/div/form[1]/div/div[1]/div/div[2]/div[5]/div[2]/div/div/a' ).click() print( f'Successfully created an unassigned job for {name_fn} {name_ln} in Jobber.' ) time.sleep(1) self.driver.close() self.driver.quit()
from selenium import webdriver from selenium.webdriver.support.select import Select import time base_url = "https://google.co.in" chrome_driver_path = r"C:\Users\nthallap\Downloads\drivers\chromedriver.exe" driver = webdriver.Chrome(executable_path=chrome_driver_path) driver.implicitly_wait(10) driver.set_page_load_timeout(30) driver.get("https://letskodeit.teachable.com/p/practice") driver.maximize_window() drop_down = driver.find_element_by_xpath("//select[@id='carselect']") sel = Select(drop_down) sel.select_by_index(2) time.sleep(3) sel.select_by_visible_text("BMW") time.sleep(3) sel.select_by_value("benz") time.sleep(3) sel.select_by_index('0') driver.quit()
import random chrome_path = r"""C:\Users\Kaleb\Documents\Tec\CyPS\chromedriver""" driver = webdriver.Chrome(chrome_path) driver.get( "http://app.sct.gob.mx/sibuac_internet/ControllerUI?action=cmdEscogeRuta") driver.find_element_by_css_selector( "#headerEPN > table:nth-child(3) > tbody > tr > td > table > tbody > tr:nth-child(3) > td > table > tbody > tr:nth-child(5) > td > a" ).click() driver.find_element_by_css_selector( "#headerEPN > table:nth-child(3) > tbody > tr > td > table > tbody > tr:nth-child(3) > td > table > tbody > tr:nth-child(14) > td > a" ).click() obj = Select(driver.find_element_by_name("edoOrigen")) obj.select_by_index(9) obj = Select(driver.find_element_by_name("edoDestino")) obj.select_by_index(23) obj = Select(driver.find_element_by_name("ciudadOrigen")) obj.select_by_index(5) obj = Select(driver.find_element_by_name("ciudadDestino")) obj.select_by_index(22) obj = Select(driver.find_element_by_name("edoIntermedio1")) obj.select_by_index(1) obj = Select(driver.find_element_by_name("ciudadIntermedia1")) obj.select_by_index(1)
def check_last30days_districts_block(self): cal = GetData() self.fname = file_extention() cal.click_on_state(self.driver) cal.page_loading(self.driver) management = self.driver.find_element_by_id('name').text management = management[16:].lower().strip() period = Select(self.driver.find_element_by_id('period')) period.select_by_index(2) timeseries = period.first_selected_option.text timeseries = timeseries.lower().replace(" ", '_') time.sleep(3) select_district = Select(self.driver.find_element_by_id('choose_dist')) select_block = Select(self.driver.find_element_by_id('choose_block')) count = 0 for x in range( len(select_district.options) - 1, len(select_district.options)): select_district.select_by_index(x) cal.page_loading(self.driver) for y in range(1, len(select_block.options)): select_block.select_by_index(y) cal.page_loading(self.driver) value = self.driver.find_element_by_id( 'choose_block').get_attribute('value') value = value.split(":") values = value[1].strip() markers = self.driver.find_elements_by_class_name(Data.dots) if len(markers) - 1 == 0: print("District" + select_district.first_selected_option.text + "Block" + select_block.first_selected_option.text + "No Data") count = count + 1 else: time.sleep(2) self.driver.find_element_by_id('download').click() time.sleep(2) p = pwd() self.filename = p.get_download_dir( ) + "/" + self.fname.sr_blockwise( ) + management + '_' + timeseries + '_allGrades__clusters_of_block_' + values + '_' + cal.get_current_date( ) + '.csv' print(self.filename) if not os.path.isfile(self.filename): print("District " + select_district.first_selected_option.text + "Block " + select_block.first_selected_option.text + "csv is not downloaded") count = count + 1 else: with open(self.filename) as fin: csv_reader = csv.reader(fin, delimiter=',') header = next(csv_reader) data = list(csv_reader) row_count = len(data) dots = len(markers) - 1 if dots != row_count: print( 'Markers records and csv file records are not matching ', dots, row_count) count = count + 1 self.remove_csv() return count
class dropdown(controlBase): def __init__(self, driver, selector: dict = None, element=None): super().__init__(driver, selector, element) self.__selectElement = Select(self.wrappedElement) @property def SelectedLabel(self): return self.__selectElement.first_selected_option.text.strip() @property def SelectedValue(self): return self.__selectElement.first_selected_option.get_attribute('value') @property def AllSelectedOptions(self): return self.__selectElement.all_selected_options def SelectByText(self, text): self.__selectElement.select_by_visible_text(text) def DeSelectByText(self, text): self.__selectElement.deselect_by_visible_text(text) def SelectByTextLike(self, text): options = self.__selectElement.options for option in options: if option.text.Contains(text): self.__selectElement.select_by_visible_text(option.text) return raise AssertionError(f'No option found with such text {text}.') def SelectByValue(self, value): self.__selectElement.select_by_value(value) def DeSelectByValue(self, value): self.__selectElement.deselect_by_value(value) def SelectByIndex(self, index): if self.HasEmptyString: self.__selectElement.select_by_index(index) else: self.__selectElement.select_by_index(index - 1) def DeSelectByIndex(self, index): if self.HasEmptyString: self.__selectElement.deselect_by_index(index) else: self.__selectElement.deselect_by_index(index-1) def DeSelectAll(self): self.__selectElement.deselect_all() @property def AllSelectedOptions(self): return self.__selectElement.all_selected_options @property def AllOptions(self): return self.__selectElement.options @property def Labels(self): if self.DoesOptionExist: return query(self.AllOptions) \ .select(lambda option: option.text.strip()).where(lambda label: label != '').to_list() else: return [] @property def HasEmptyString(self): if self.DoesOptionExist: return query(self.AllOptions) \ .select(lambda option: option.text.strip()).any(lambda label: label == '') else: return True @property def Options(self): return query(self.AllOptions).select(lambda e: dropdownOption(self.webDriver, None, e)) @property def Values(self): if self.DoesOptionExist: return query(self.AllOptions) \ .select(lambda option: option.get_attribute('value')).where(lambda value: value != '').to_list() else: return [] @property def IsMultiSelectDropDown(self): return self.__selectElement.is_multiple @property def DoesOptionExist(self): return self.__selectElement.options is not None
page.append(content) wb.save(filename=workbook_name) # write your pids here to search with pids = ["002-630-141", "002-630-141"] driver = webdriver.Firefox() driver.set_page_load_timeout(1000) #1000 seconds url = "https://www.bcassessment.ca/Property/AssessmentSearch?bcalogin=1" driver.get(url) for pid in pids: select_fr = Select(driver.find_element_by_id("ddlSearchType")) select_fr.select_by_index(3) data = [] driver.find_element_by_name("searchPID").send_keys(pid) driver.find_element_by_id("btnSearch").click() #time.sleep(20) delay = 100 # seconds try: myElem = WebDriverWait(driver, delay).until( EC.presence_of_element_located((By.ID, 'mainaddresstitle'))) print("Page is ready!") except TimeoutException: print("Loading took too much time!")
'//p[@id="ticket_tit_id"]/strong[@class="ml5"]').text for i, passerger in enumerate(ticket_12306_config_dict['passenger_list']): selector = Select(driver.find_element_by_id("seatType_" + str(i + 1))) select_seat_list = [ o.text.replace(' ', '').replace('\n', '') for o in selector.options ] print_t('自动选择座位类型,目前可选择的座位类型有', select_seat_list) set_seat_success = False for train_seat in ticket_12306_config_dict['train_seat']: for i, select_seat in enumerate(select_seat_list): if select_seat.find(train_seat) > -1 and not set_seat_success: print_t('为', passerger, '自动选择座位类型,目前为你成功选择座位类型为', train_seat) selector.select_by_index(i) set_seat_success = True break print_t('自动点击提交购票按钮') driver.find_element_by_id("submitOrder_id").click() print_t('等待确认购买按钮加载完成') try: WebDriverWait(driver, 10, 0.1).until( lambda x: x.find_element_by_id("qr_submit_id").is_displayed()) except Exception as e: if isinstance(e, TimeoutException): print_t('网络超时,即将退出,请确认网络后发起重试') else: print(e)
from selenium import webdriver from selenium.webdriver.support.select import Select from selenium.webdriver.common.by import By driver = webdriver.Chrome("./chromedriver") driver.get("https://rahulshettyacademy.com/angularpractice/") driver.find_element(By.CSS_SELECTOR, "input[name='name']").send_keys("Test") driver.find_element(By.NAME, "email").send_keys("*****@*****.**") driver.find_element(By.ID, "exampleInputPassword1").send_keys("test123") driver.find_element(By.ID, "exampleCheck1").click() dropdown = Select(driver.find_element(By.ID, "exampleFormControlSelect1")) dropdown.select_by_visible_text( "Female") #When the dropdown options are visible dropdown.select_by_index("0") #Index of the dropdown options driver.find_element(By.CSS_SELECTOR, "input[name='inlineRadioOptions']").click() driver.find_element(By.XPATH, "//input[@type='submit']").click() message = driver.find_element(By.CLASS_NAME, "alert-success").text print(message) assert "Success" in message
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.select import Select import time driver=webdriver.Chrome(executable_path="C:\DriverChrome\chromedriver") driver.maximize_window() driver.get("https://login.aol.com/account/create?lang=es-ES&src=oauth&done=https%3A%2F%2Fapi.login.aol.com%2Foauth2%2Frequest_auth%3Fresponse_type%3Dcode%26client_id%3DGzkftzubVdjySPGg%26redirect_uri%3Dhttps%253A%252F%252Flogin.yahoo.com%252Faccount%252Fchallenge%252Ftpa%252Fredirect%26scope%3Dopenid%2520sdpp-r%2520openid2%26ui_locales%3Des-ES%26state%3Dacrumb%253D0Xj35vqY%257Cactivity%253Duh-signin%257Cpspid%253D1185550002%257Csrc%253Dfinance%257CsessionIndex%253DQQ--%257Cdisplay%253Dlogin%257CauthMechanism%253Dprimary%257Cintl%253Des%257Clang%253Des-ES&specId=yidReg") month=driver.find_element(By.ID,"usernamereg-month") monthDD=Select(month) ddlist=monthDD.options monthDD.select_by_index(3) time.sleep(2) monthDD.select_by_value("6") time.sleep(2) monthDD.select_by_visible_text("Diciembre") time.sleep(2) #Usefull to know how many elements there are into a list print(len(ddlist)) assert 13== len(ddlist) for ele in ddlist: print("Value is ", ele.text) if ele.text=="Octubre": ele.click() time.sleep(3) break
driver.find_element_by_id("inputPassword3").send_keys("PAss@1234") driver.find_element_by_xpath("//button[@type='button']").click() wait = WebDriverWait(driver, 50) wait.until( expected_conditions.presence_of_element_located( (By.XPATH, '//body/ui-view[1]/div[1]/aside[1]/section[1]/ul[1]/li[3]/a[1]'))) driver.find_element_by_xpath( "//body/ui-view[1]/div[1]/aside[1]/section[1]/ul[1]/li[3]/a[1]").click() wait.until( expected_conditions.presence_of_element_located( (By.XPATH, "//section/ul[@class='sidebar-menu']/li[3]/ul/li[2]/a"))) indvCustom = driver.find_element_by_xpath( "//section/ul[@class='sidebar-menu']/li[3]/ul/li[2]/a") time.sleep(5) ActionChains(driver).move_to_element(indvCustom).click(indvCustom).perform() time.sleep(5) branchName = Select(driver.find_element_by_css_selector("#customerBranchId")) branchName.select_by_visible_text("Head Office") time.sleep(3) spokeName = Select(driver.find_element_by_id("centreId")) spokeName.select_by_index(1) time.sleep(3) gallery = driver.find_element_by_xpath( "//div[@id='PERSONAL_INFORMATION']//div//button") gallery.send_keys("C:\\Users\\vidya\\Downloads\\image.jpg") # driver.back() # driver.refresh()
def selector_by_index(self, locator, index): selector = Select(self.find_element(locator)) try: selector.select_by_index(index) except: print("下拉框元素未找到")
class BasePage: """Base class for page objects""" driver: WebDriver def __init__(self, webdriver, cfg): """base initialization""" self.webdriver = webdriver self.cfg = cfg self.query_execution_area = '//*[@id="aqlEditor"]' self.bindvalues_area = '//*[@id="bindParamAceEditor"]' self.locator = None self.select = None self.current = None @classmethod def set_up_class(cls): """This method will be used for the basic driver setup""" # browser_list = ['1 = chrome', '2 = firefox', '3 = edge', '4 = chromium'] # print(*browser_list, sep="\n") # cls.browser_name = None # while cls.browser_name not in {1, 2, 3, 4}: # cls.browser_name = int(input('Choose your browser: ')) # # if cls.browser_name == 1: # print("You have chosen: Chrome browser \n") # cls.driver = webdriver.Chrome(ChromeDriverManager().install()) # elif cls.browser_name == 2: # print("You have chosen: Firefox browser \n") # # # This preference will disappear download bar for firefox # profile = webdriver.FirefoxProfile() # profile.set_preference("browser.helperApps.neverAsk.saveToDisk", "application/json, text/csv") # mime # profile.set_preference("browser.download.manager.showWhenStarting", False) # profile.set_preference("browser.download.dir", "C:\\Users\\rearf\\Downloads") # profile.set_preference("browser.download.folderList", 2) # profile.set_preference("pdfjs.disabled", True) # # cls.driver = webdriver.Firefox(executable_path=GeckoDriverManager().install(), firefox_profile=profile) # # elif cls.browser_name == 3: # print("You have chosen: Edge browser \n") # cls.driver = webdriver.Edge(EdgeChromiumDriverManager().install()) # elif cls.browser_name == 4: # print("You have chosen: Chromium browser \n") # cls.driver = webdriver.Chrome(ChromeDriverManager(chrome_type=ChromeType.CHROMIUM).install()) # else: # print("Kindly provide a specific browser name from the list. \n") # cls.driver.set_window_size(1250, 1000) # custom window size # cls.driver.get("http://127.0.0.1:8529/_db/_system/_admin/aardvark/index.html#login") @classmethod def tear_down(cls): """This method will be used for teardown the driver instance""" time.sleep(5) # cls.driver.close() print("\n--------Now Quiting--------\n") # cls.driver.quit() def switch_to_iframe(self, iframe_id): """This method will switch to IFrame window""" self.webdriver.switch_to.frame( self.webdriver.find_element(BY.XPATH, iframe_id)) time.sleep(1) def switch_back_to_origin_window(self): """This method will switch back to origin window""" self.webdriver.switch_to.default_content() time.sleep(1) def wait_for_ajax(self): """wait for jquery to finish...""" wait = WebDriverWait(self.webdriver, 15) try: wait.until(lambda driver: driver.execute_script( "return (typeof jQuery !== 'undefined') && jQuery.active") == 0 ) wait.until(lambda driver: driver.execute_script( "return document.readyState") == "complete") except TimeoutException: pass def clear_all_text(self, locator=None): """This method will select all text and clean it""" print("Cleaning input field \n") if locator is not None: locator = self.locator_finder_by_xpath(locator) print("Cleaning input field \n") actions = ActionChains(self.webdriver) actions.click(locator) actions.key_down(Keys.CONTROL) actions.send_keys("a") actions.send_keys(Keys.DELETE) actions.key_up(Keys.CONTROL) actions.perform() def check_ui_responsiveness(self): """Checking LOG tab causes unresponsive UI (found in 3.8 server package""" print("\n") print("Clicking on Log tab \n") log = "logs" log = self.locator_finder_by_id(log) log.click() print("Try to tap on Log Level drop down button \n") log_level = "logLevelSelection" log_level = self.locator_finder_by_id(log_level) log_level.click() time.sleep(3) print("Close the Log Level button \n") log_level01 = "closeFilter" log_level01 = self.locator_finder_by_id(log_level01) log_level01.click() print("Quickly tap on to Collection Tab") collection = "collections" collection = self.locator_finder_by_id(collection) collection.click() print("Waiting for few seconds \n") time.sleep(3) print("Return back to Log tab again \n") log01 = "logs" log01 = self.locator_finder_by_id(log01) log01.click() print("Trying to tap on Log Level once again \n") try: log_level = "logLevelSelection" log_level = self.locator_finder_by_id(log_level) log_level.click() assert "Level" in log_level.text, "********UI become unresponsive******" if log_level.text == "Level": print("Ui is responsive and working as usual\n") except TimeoutException: print("********Dashboard responsiveness check failed********") time.sleep(2) print("UI responsiveness test completed \n") print("Back to Dashboard again \n") self.webdriver.refresh() dash = "dashboard" dash = self.locator_finder_by_id(dash) dash.click() time.sleep(2) def select_query_execution_area(self): """This method will select the query execution area""" try: query_sitem = self.locator_finder_by_xpath( self.query_execution_area) query_sitem.click() time.sleep(2) except TimeoutException: print("Can't find the query execution area \n") def select_bindvalue_json_area(self): """This method will select the query execution area""" try: query_sitem = self.locator_finder_by_xpath(self.bindvalues_area) query_sitem.click() time.sleep(2) except TimeoutException: print("Can't find the query execution area \n") def query_execution_btn(self): """Clicking execute query button""" execute = "executeQuery" execute = self.locator_finder_by_id(execute) execute.click() time.sleep(2) def send_key_action(self, key): """This method will send dummy data to the textfield as necessary""" actions = ActionChains(self.webdriver) actions.send_keys(key) actions.perform() def clear_text_field(self, locator): """This method will be used for clear all the text in single text field if .clear() does not work""" locator.send_keys(Keys.CONTROL + "a", Keys.BACKSPACE) if self.locator is None: raise Exception("UI-Test: ", locator, " locator was not found.") return self.locator def switch_tab(self, locator): """This method will change tab and close it and finally return to origin tab""" print("switching tab method \n") self.locator = locator self.locator.send_keys( Keys.CONTROL, Keys.RETURN) # this will open new tab on top of current self.webdriver.switch_to.window( self.webdriver.window_handles[1] ) # switch to new tab according to index value title = self.webdriver.title print("Current page title: ", title, "\n") time.sleep(15) self.webdriver.close() # closes the browser active window self.webdriver.switch_to.window(self.webdriver.window_handles[0]) return title def check_version_is_newer(self, compare_version): """ check whether the version in the ui is the expected """ ui_version_str = self.locator_finder_by_id("currentVersion").text print("Package Version: ", ui_version_str) ui_version = semver.VersionInfo.parse(ui_version_str) compare_version = semver.VersionInfo.parse(compare_version) return ui_version >= compare_version def current_package_version(self): """checking current package version from the dashboard""" package_version = "currentVersion" package_version = self.locator_finder_by_id(package_version).text print("Package Version: ", package_version) return semver.VersionInfo.parse(package_version) def current_user(self): """get the currently logged in user from the page upper middle""" self.wait_for_ajax() userbar_sitem = self.locator_finder_by_id("userBar") return str(userbar_sitem.find_element(BY.CLASS_NAME, "toggle").text) def current_database(self): """get the currently used database from the page upper middle""" self.wait_for_ajax() database_sitem = self.locator_finder_by_id("dbStatus") return database_sitem.find_element(BY.CLASS_NAME, "state").text def scroll(self, down=0): """This method will be used to scroll up and down to any page""" # TODO: do this instead of sleep? # https://sqa.stackexchange.com/questions/35589/how-to-wait-for-javascript-scroll-action-to-finish-in-selenium if down == 1: self.webdriver.find_element(BY.TAG_NAME, "html").send_keys(Keys.END) print("") time.sleep(3) else: time.sleep(5) self.webdriver.find_element(BY.TAG_NAME, "html").send_keys(Keys.HOME) # self.webdriver.execute_script("window.scrollTo(0,500)") def locator_finder_by_idx(self, locator_name, timeout=10): """This method will used for finding all the locators by their id""" print(locator_name) self.locator = WebDriverWait(self.webdriver, timeout).until( EC.presence_of_element_located((BY.ID, locator_name)), message="UI-Test: " + locator_name + " locator was not found.", ) if self.locator is None: raise Exception(locator_name, " locator was not found.") return self.locator def locator_finder_by_id(self, locator_name, timeout=10): """This method will used for finding all the locators by their id""" print(locator_name) self.locator = WebDriverWait(self.webdriver, timeout).until( EC.element_to_be_clickable((BY.ID, locator_name)), message="UI-Test: " + str(locator_name) + " locator was not found.", ) if self.locator is None: raise Exception(str(locator_name), " locator was not found.") return self.locator def locator_finder_by_xpath(self, locator_name, timeout=10, expec_fail=False): """This method will used for finding all the locators by their xpath""" try: self.locator = WebDriverWait(self.webdriver, timeout).until( EC.element_to_be_clickable((BY.XPATH, locator_name)), message="UI-Test: " + locator_name + " locator was not found.", ) except Exception as ex: if expec_fail: raise ex ti.prompt_user( self.cfg, "ERROR " * 10 + "\nError while wating for web element:\n" + str(ex) + "\n" + "".join(traceback.format_stack(ex.__traceback__.tb_frame))) raise ex if self.locator is None: raise Exception("UI-Test: ", locator_name, " locator was not found.") return self.locator def locator_finder_by_link_text(self, locator_name): """This method will be used for finding all the locators by their xpath""" self.locator = WebDriverWait(self.webdriver, 10).until( EC.element_to_be_clickable((BY.LINK_TEXT, locator_name))) if self.locator is None: print("UI-Test: ", locator_name, " locator has not found.") else: return self.locator def locator_finder_by_select(self, locator_name, value): """This method will used for finding all the locators in drop down menu with options""" self.select = Select(self.webdriver.find_element(BY.ID, locator_name)) self.select.select_by_index(value) if self.select is None: raise Exception("UI-Test: ", locator_name, " locator was not found.") return self.select def select_value(self, locator_name, value): """Select given value in drop down menu""" self.select = Select(self.webdriver.find_element(BY.ID, locator_name)) if self.select is None: raise Exception("UI-Test: ", locator_name, " locator was not found.") self.select.select_by_value(value) def locator_finder_by_select_using_xpath(self, locator_name, value): """This method will used for finding all the locators in drop down menu with options using xpath""" self.select = Select( self.webdriver.find_element(BY.XPATH, locator_name)) self.select.select_by_index(value) if self.select is None: print("UI-Test: ", locator_name, " locator has not found.") return self.select def locator_finder_by_class(self, locator_name): """This method will used for finding all the locators by their id""" self.locator = WebDriverWait(self.webdriver, 10).until( EC.element_to_be_clickable((BY.CLASS_NAME, locator_name))) if self.locator is None: print(locator_name, " locator has not found.") return self.locator def locator_finder_by_hover_item_id(self, locator): """This method will used for finding all the locators and hover the mouse by id""" item = self.webdriver.find_element(BY.ID, locator) action = ActionChains(self.webdriver) action.move_to_element(item).click().perform() time.sleep(1) return action def zoom(self): """This method will used for zoom in/out on any perspective window""" print("zooming in now\n") self.webdriver.execute_script("document.body.style.zoom='80%'") def locator_finder_by_hover_item(self, locator): """This method will used for finding all the locators and hover the mouse by xpath""" item = self.webdriver.find_element(BY.XPATH, locator) action = ActionChains(self.webdriver) action.move_to_element(item).click().perform() time.sleep(1) return action def locator_finder_by_css_selectors(self, locator_name, timeout=10): """This method will used for finding all the locators text using CSS Selector""" self.locator = WebDriverWait(self.webdriver, timeout).until( EC.element_to_be_clickable((BY.CSS_SELECTOR, locator_name)), message="UI-Test: " + locator_name + " locator was not found.", ) self.locator = self.locator.text if self.locator is None: raise Exception("UI-Test: ", locator_name, " locator was not found.") return self.locator # pylint: disable=too-many-arguments def check_expected_error_messages_for_analyzer(self, error_input, print_statement, error_message, locators_id, error_message_id, div_id=None): """This method will take three lists and check for expected error condition against user's inputs""" i = 0 # looping through all the error scenario for test # print('len: ', len(name_error)) while i < len( error_input ): # error_input list will hold a list of error inputs from the users print( print_statement[i] ) # print_statement will hold a list of all general print statements for the test locators = locators_id # locator id of the input placeholder where testing will take place if div_id is not None: locator_sitem = self.locator_finder_by_xpath(locators) else: locator_sitem = self.locator_finder_by_id(locators) locator_sitem.click() locator_sitem.clear() locator_sitem.send_keys(error_input[i]) time.sleep(1) locator_sitem.send_keys(Keys.TAB) time.sleep(1) if div_id is not None: create_btn = f"/html/body/div[{div_id}]/div/div[3]/button[2]" create_btn_sitem = self.locator_finder_by_xpath(create_btn) create_btn_sitem.click() time.sleep(2) try: # placeholder's error message id error_sitem = BasePage.locator_finder_by_xpath( self, error_message_id).text print("Expected error found: ", error_sitem, "\n") time.sleep(2) error_sitem = self.locator_finder_by_xpath( error_message_id).text # error_message list will hold expected error messages assert ( error_sitem == error_message[i] ), f"FAIL: Expected error message {error_message[i]} but got {error_sitem}" print("x" * (len(error_sitem) + 29)) print("OK: Expected error found: ", error_sitem) print("x" * (len(error_sitem) + 29), "\n") time.sleep(2) except TimeoutException as ex: raise Exception( "*****-->Error occurred. Manual inspection required<--***** \n" ) from ex i = i + 1 # pylint: disable=too-many-arguments def check_expected_error_messages_for_database(self, error_input, print_statement, error_message, locators_id, error_message_id, value=False): """This method will take three lists and check for expected error condition against user's inputs""" # value represent true because cluster rf and write concern has different wat to catch the error i = 0 # looping through all the error scenario for test while i < len( error_input ): # error_input list will hold a list of error inputs from the users print( print_statement[i] ) # print_statement will hold a list of all general print statements for the test locators = locators_id # locator id of the input placeholder where testing will take place locator_sitem = self.locator_finder_by_id(locators) locator_sitem.click() locator_sitem.clear() locator_sitem.send_keys(error_input[i]) time.sleep(2) if semver.VersionInfo.parse( "3.8.0") <= self.current_package_version( ) <= semver.VersionInfo.parse("3.8.100"): locator_sitem.send_keys(Keys.TAB) time.sleep(2) try: # trying to create the db for >= v3.9.x if value is False and self.current_package_version( ) >= semver.VersionInfo.parse("3.9.0"): self.locator_finder_by_xpath( '//*[@id="modalButton1"]').click() time.sleep(2) # placeholder's error message id for 3.9 error_sitem = self.locator_finder_by_xpath( error_message_id).text elif value is False and self.current_package_version( ) == semver.VersionInfo.parse("3.8.0"): error_sitem = self.locator_finder_by_xpath( error_message_id).text else: error_sitem = self.locator_finder_by_xpath( error_message_id).text # error_message list will hold expected error messages assert ( error_sitem == error_message[i] ), f"FAIL: Expected error message {error_message[i]} but got {error_sitem}" print("x" * (len(error_sitem) + 29)) print("OK: Expected error found: ", error_sitem) print("x" * (len(error_sitem) + 29), "\n") time.sleep(2) # getting out from the db creation for the next check if value is False and self.current_package_version( ) >= semver.VersionInfo.parse("3.9.0"): self.webdriver.refresh() self.locator_finder_by_id("createDatabase").click() time.sleep(1) except TimeoutException as ex: raise Exception( "*****-->Error occurred. Manual inspection required<--***** \n" ) from ex i = i + 1 def check_expected_error_messages_for_views(self, error_input, print_statement, error_message, locators_id, error_message_id): """This method will take three lists and check for expected error condition against user's inputs""" # looping through all the error scenario for test i = 0 while i < len( error_input ): # error_input list will hold a list of error inputs from the users print( print_statement[i] ) # print_statement will hold a list of all general print statements for the test # locator id of the input placeholder where testing will take place locator_sitem = self.locator_finder_by_xpath(locators_id) locator_sitem.click() locator_sitem.clear() locator_sitem.send_keys(error_input[i]) time.sleep(2) if self.current_package_version() >= semver.VersionInfo.parse( "3.8.0"): locator_sitem.send_keys(Keys.TAB) time.sleep(2) try: # trying to create the views error_sitem = self.locator_finder_by_xpath( error_message_id).text # error_message list will hold expected error messages assert error_sitem == error_message[i], \ f"FAIL: Expected error message {error_message[i]} but got {error_sitem}" print('x' * (len(error_sitem) + 29)) print('OK: Expected error found: ', error_sitem) print('x' * (len(error_sitem) + 29), '\n') time.sleep(2) except TimeoutException as ex: raise Exception( "*****-->Error occurred. Manual inspection required<--***** \n" ) from ex i = i + 1 def check_server_package(self): """This will determine the current server package type""" try: package = self.locator_finder_by_id("communityLabel").text return package except TimeoutException: print("This is not a Community server package.\n") try: package = self.locator_finder_by_id("enterpriseLabel").text return package except TimeoutException: print("This is not a Enterprise server package.\n") return "package not found" def choose_item_from_a_dropdown_menu(self, element: WebElement, item_text: str): """Given a drop-down menu element, click on it to open the menu and then click on an item with given text.""" element.click() item_locator = """//ul[@class="select2-results"]/li/div[text()='%s']""" % item_text item_element = self.locator_finder_by_xpath(item_locator) item_element.click() def click_submenu_entry(self, text): """click submenu""" locator = """//li[contains(@class, 'subMenuEntry')]/a[text()='%s']""" % text self.locator_finder_by_xpath(locator).click() # pylint: disable=no-self-use def progress(self, arg): """state print""" # todo print(arg) def xpath(self, path): """shortcut xpath""" return self.webdriver.find_element(BY.XPATH, path) def by_class(self, classname): """shortcut class-id""" return self.webdriver.find_element(BY.CLASS_NAME, classname) def handle_red_bar(self): """It will check for any red bar error notification""" try: notification = 'noty_body' notification = (self.locator_finder_by_class(notification)) time.sleep(2) print("*" * 100) print(notification.text) print("*" * 100) return notification.text except TimeoutException: print('No error/warning found!') return None
#identify the Google search text box and enter the value driver.find_element_by_name("q").send_keys("https://opensource-demo.orangehrmlive.com/index.php/auth/login") # time.sleep(3) #click on the Google search button driver.find_element_by_name("btnK").submit() time.sleep(3) driver.find_element_by_class_name("LC20lb").click() driver.find_element_by_name("txtUsername").send_keys("Admin") driver.find_element_by_name("txtPassword").send_keys("admin123") driver.find_element_by_name("Submit").click() driver.find_element_by_id("menu_admin_viewAdminModule").click() driver.find_element_by_id("menu_admin_UserManagement").click() driver.find_element_by_id("menu_admin_viewSystemUsers").click() driver.find_element_by_name("searchSystemUser[userName]").send_keys("a1123") dropdown = Select(driver.find_element_by_id("searchSystemUser_userType")) dropdown.select_by_index(2) driver.find_element_by_id("searchSystemUser_employeeName_empName").send_keys("Fiona Grace") select = Select(driver.find_element_by_id("searchSystemUser_status")) select.select_by_index(1) driver.find_element_by_id("searchBtn").click() # driver.switch_to.window(driver.find_element_by_link_text("saveSystemUser?userId=18")).click() driver.find_element_by_name("btnAdd").click() select1 = Select(driver.find_element_by_name("systemUser[userType]")) select1.select_by_index(1) driver.find_element_by_id("systemUser_employeeName_empName").send_keys("Fiona Grace") driver.find_element_by_name("systemUser[userName]").send_keys("02suraj45") select2 = Select(driver.find_element_by_name("systemUser[status]")) select2.select_by_index(0) driver.find_element_by_name("systemUser[password]").send_keys("suraj123")
def select_term(index): driver.switch_to_frame(driver.find_element(By.XPATH,'//iframe[@name="TargetContent"]')) time.sleep(10) select = Select(driver.find_element(By.XPATH,'//div[@id="win0divCLASS_SRCH_WRK2_STRM$35$"]/select')) select.select_by_index(int(index)) driver.switch_to_default_content()
def test_select_vehicle_ownername(self): element1 = driver.find_element_by_xpath("//select[@name='owner_id']") sel = Select(element1) sel.select_by_index(2) time.sleep(3)
def select_course_career(index): driver.switch_to_frame(driver.find_element(By.XPATH,'//iframe[@name="TargetContent"]')) time.sleep(10) select = Select(driver.find_element(By.XPATH,'//div[@id="win0divCLASS_SRCH_WRK2_ACAD_CAREER"]/select')) select.select_by_index(index) driver.switch_to_default_content()
def test_select_vehicle_type(self): element2 = driver.find_element_by_xpath( "//select[@name='vehicle_type_id']") sel2 = Select(element2) sel2.select_by_index(2)