How to use get_current_browser method in robotframework-pageobjects

Best Python code snippet using robotframework-pageobjects_python

WebElementAction.py

Source:WebElementAction.py Github

copy

Full Screen

...129 def execute_javascript(self, script_name):130 '''131 execute java script132 '''133 self._browser.get_current_browser().execute_script(script_name)134 135 def choose_file(self, locator, file_path):136 """Inputs the `file_path` into file input field found by `locator`.137 This keyword is most often used to input files into upload forms.138 The file specified with `file_path` must be available on the same host 139 where the Selenium is running.140 """141 if not os.path.isfile(file_path):142 log.mjLog.LogReporter("WebUIOperation","debug","choose_file - File '%s' does not exist on the \143 local file system" % file_path)144 self.element = self._element_finder(locator)145 if self.element:146 self.element.send_keys(file_path)147 log.mjLog.LogReporter("WebUIOperation","debug","choose_file - File '%s' selected" % file_path)148 def double_click_element(self, locator):149 """Double click element identified by `locator`.150 Key attributes for arbitrary elements are `id` and `name`151 """152 self.element = self._element_finder(locator)153 if self.element:154 ActionChains(self._browser.get_current_browser()).double_click(self.element).perform()155 log.mjLog.LogReporter("WebUIOperation","debug","double_click_element operation \156 successful- %s" %(locator)) 157 158 def drag_and_drop(self, source, target):159 """Drags element identified with `source` which is a locator.160 Element can be moved on top of another element with `target`161 argument.162 `target` is a locator of the element where the dragged object is163 dropped.164 """165 self.source_ele = self._element_finder(source)166 self.target_ele = self._element_finder(target)167 168 if self.source_ele and self.target_ele:169 ActionChains(self._browser.get_current_browser()).drag_and_drop(self.source_ele, self.target_ele).perform()170 log.mjLog.LogReporter("WebUIOperation","debug","drag_and_drop operation \171 successful: %s -> %s" %(source, target))172 173 def drag_and_move(self, source, target):174 """Drags element identified with `source` which is a locator.175 Element can be moved on top of another element with `target`176 argument.177 `target` is a locator of the element where the dragged object is178 dropped.179 """180 self.source_ele = self._element_finder(source)181 self.target_ele = self._element_finder(target)182 183 if self.source_ele and self.target_ele:184 185 ActionChains(self._browser.get_current_browser()).click_and_hold(self.source_ele).move_to_element(self.target_ele).perform()186 def right_click(self, locator):187 '''Right Click on element identified by `locator`.188 Key attributes for arbitrary elements are `id` and `name`189 '''190 self.element = self._element_finder(locator)191 if self.element:192 ActionChains(self._browser.get_current_browser()).context_click(self.element).perform()193 log.mjLog.LogReporter("WebUIOperation", "debug", "right_click operation \194 successful- %s" % (locator))195 def explicit_wait(self, element, waittime=20, replace_dict=None, ec='visibility_of_element_located', msg=None, msg_to_verify=None, condition_category="until"):196 """197 explicit_wait() is used to wait until element is displayed & enabled198 element: the web element199 waittime: max time to wait200 replace_dict: to replace variables in the value in map file. Refer _map_converter function in browser.py for more info201 ec: expected condition to wait on202 msg: msg to be validated irrespective of the element e.g. title_is or title_contains203 msg_to_verify: msg to be validated on a web element e.g. text_to_be_present_in_element204 condition_category = category of conditions to verify with until being default. To make the condition checking to until_not pass this205 parameter as until_not while calling this function. Example below206 e.g.207 For a map file entry as below208 comp_name==span#xpath#//*[@id="companyName"]209 some example calls to this function could be210 r = self.action_ele.explicit_wait("comp_name")211 r = self.action_ele.explicit_wait("comp_name",ec="title_contains",msg="Account") # "comp_name" i.e. element is not required212 in this call but it is required as it is a mandatory argument. It is this way to make this function backward compatible213 r = self.action_ele.explicit_wait("comp_name", ec="text_to_be_present_in_element", msg_to_verify="M5Portal Company")214 There are some custom expected conditions as well. They are implemented in the custom_expected_conditions.py file.215 Some of the custom wats are length_of_drop_down_is,drop_down_has_option etc.216 Example usage is given below:217 # to wait till the length of drop down grows more than 5218 mydrop_down = self.action_ele.explicit_wait('Peopleselect_dropbox', ec="length_of_drop_down_is", msg_to_verify=5)219 # to wait till the given drop down has an option "ff ll"220 mydrop_down = self.action_ele.explicit_wait('Peopleselect_dropbox', ec="drop_down_has_option", msg_to_verify="ff ll")221 self.action_ele.explicit_wait('SwitchAcc_ok', ec="visibility_of_element_located",condition_category="until_not")222 """223 if element[0:2] == "//":224 self.elementAttr = {225 "ELEMENT_TYPE": "unused placeholder",226 "BY_TYPE": "xpath",227 "BY_VALUE": element228 }229 else:230 self.elementAttr = self._browser._map_converter(element, replace_dict)231 if 'not' in condition_category:232 wait = WebDriverWait(self._browser.get_current_browser(), waittime).until_not233 error_msg = "The element <%s> can still be located after explicit wait." % element234 else:235 wait = WebDriverWait(self._browser.get_current_browser(), waittime).until236 error_msg = "Could not locate element <%s> during explicit wait." % element237 result = None238 try:239 condition = getattr(EC, ec)240 except AttributeError as e:241 condition = getattr(CEC, ec)242 locator = getattr(By, self.elementAttr['BY_TYPE'].upper())243 try:244 if msg:245 result = wait(condition(msg))246 elif msg is None and msg_to_verify is None:247 result = wait(condition((locator, self.elementAttr["BY_VALUE"])))248 elif msg_to_verify:249 result = wait(condition((locator, self.elementAttr["BY_VALUE"]), msg_to_verify))250 except Exception as e:251 raise Exception(error_msg + str(e))252 return result253 def focus(self, locator):254 """Sets focus to element identified by `locator`."""255 256 self.element = self._element_finder(locator)257 self._current_browser().execute_script("arguments[0].focus();", self.element)258 log.mjLog.LogReporter("WebUIOperation","debug","focus operation successful: %s" %(locator))259 260 def alert_action(self, Cancel= False):261 """Dismisses currently shown alert dialog and returns it's message.262 By default, this keyword chooses 'OK' option from the dialog. If263 'Cancel' needs to be chosen, set keyword ` Cancel = True'264 """265 self.text = self._alert(Cancel)266 log.mjLog.LogReporter("WebUIOperation","debug","alert_action successful:Text => %s" %(self.text))267 return self.text268 269 def press_key(self, locator, key):270 """Simulates user pressing key on element identified by `locator`.271 `key` is a single character.272 Examples:273 press_key ("GoogleSearch", "BACKSPACE")274 """275 if len(key) < 1:276 log.mjLog.LogReporter("WebUIOperation","error","press_key - Key value \277 not present - %s" %(key))278 return None279 keydict = self._map_ascii_key_code_to_key(key)280 #if len(key) > 1:281 # raise ValueError("Key value '%s' is invalid.", key)282 self.element = self._element_finder(locator)283 #select it284 if self.element:285 self.element.send_keys(keydict)286 log.mjLog.LogReporter("WebUIOperation","debug","press_key - Key %s sent \287 successfully " %(key))288 289 def mouse_hover(self, locator):290 '''Mouse hover on element identified by `locator`.291 Key attributes for arbitrary elements are `id` and `name`292 '''293 self.element = self._element_finder(locator)294 if self.element:295 ActionChains(self._browser.get_current_browser()).move_to_element(self.element).perform()296 log.mjLog.LogReporter("WebUIOperation","debug","mouse_hover operation \297 successful- %s" %(locator))298 def switch_to_frame(self,frameno):299 '''300 switch to frame('frameno') 301 '''302 self.framelist=self._browser.elements_finder("UCB_Frame")303 self.browserdriver=self._browser.get_current_browser()304 self.browserdriver.switch_to_frame(self.framelist[frameno])305 def select_from_dropdown_using_text(self,locator,itemtext):306 ''' Selecting item from dropdownlist by using the option itemtext307 308 '''309 selectionlist=self._element_finder(locator)310 for option in selectionlist.find_elements_by_tag_name('option'):311 if option.text.strip() == itemtext :312 option.click()313 log.mjLog.LogReporter("WebUIOperation","debug","select_form_dropdown using text \314 successful- %s" %(itemtext))315 def select_from_dropdown_using_index(self,locator,itemindex):316 ''' Selecting item from dropdownlist by using the option itemindex317 318 '''319 selectionlist=self._element_finder(locator)320 sel = Select(selectionlist)321 for option in selectionlist.find_elements_by_tag_name('option'):322 if option.get_attribute("index") == str(itemindex):323 #self._setSelected(option)324 sel.select_by_index(itemindex)325 log.mjLog.LogReporter("WebUIOperation","debug","select_form_dropdown using index \326 successful- %s" %(itemindex))327 def select_list_item_using_text(self,locator,itemtext):328 '''329 select item from list by using itemtext330 '''331 # below change is to take care of new dropdown implementation332 selectlist=self._browser.elements_finder(locator)333 for item in selectlist:334 if item.text==itemtext:335 item.click()336 log.mjLog.LogReporter("WebUIOperation","debug","select_list_item form list \337 successful- %s" %(itemtext))338 break339 def select_list_item_using_index(self,locator,itemindex):340 '''341 select item from list by using itemindex342 '''343 selectlist=self._element_finder(locator)344 for item in selectlist:345 if item[index]==itemindex:346 item[index].click()347 log.mjLog.LogReporter("WebUIOperation","debug","select_list_item form list \348 successful- %s" %(itemindex))349 350 def close_window(self):351 '''352 closes the current window353 '''354 self.browserdriver = self._browser.get_current_browser()355 self.browserdriver.close()356 self.window_list = self.browserdriver.window_handles357 def switch_to_window(self,window):358 '''359 switch to window('window') or360 can be used to switch to a tab361 switch_to_window(1)362 switch_to_window(2)363 the index number is the index of tab based on the order of tab opening364 '''365 self.browserdriver = self._browser.get_current_browser()366 self.window_list = self.browserdriver.window_handles367 self.browserdriver.switch_to.window(self.window_list[window])368 369 370 def scroll(self, locator, position=1000):371 '''Scrolls from top to desired position at bottom372 locator is the id or class of scroll bar not exactly xpath373 position is the value of the place till where you want to scroll374 pass position=0 for scrolling from bottom to top375 '''376 self.xpath = self._browser._map_converter(locator)["BY_VALUE"]377 self.type = self._browser._map_converter(locator)["ELEMENT_TYPE"]378 if self.type == "id" :379 scriptName = "$(document).ready(function(){$('#"+self.xpath+"').scrollTop("+str(position)+");});"380 self._browser.get_current_browser().execute_script(scriptName)381 else:382 scriptName = "$(document).ready(function(){$('."+self.xpath+"').scrollTop("+str(position)+");});"383 self._browser.get_current_browser().execute_script(scriptName)384 385 def input_text_basic(self, locator, text):386 """sets the given 'text' into the field identified by 'locator'387 extra info: This method performs operation on HTML element called time388 Eg: if you want to set time then pass the time parameter in form of 'hhmm'389 """390 self.element = self._element_finder(locator)391 if self.element:392 self.element.send_keys(text)393 log.mjLog.LogReporter("WebUIOperation","debug","input_text_basic operation successful- %s" %(locator))394 def window_handles_count(self):395 '''396 Get window handles count 397 '''398 self.browserdriver=self._browser.get_current_browser()399 self.window_list = self.browserdriver.window_handles400 return len(self.window_list)401 def check_checkbox(self, locator):402 """Checks if checkbox identified by `locator` is selected or unselected403 """404 self.element = self._element_finder(locator)405 if self.element.is_selected():406 log.mjLog.LogReporter("WebUIOperation","debug","check_checkbox operation successful- %s" %(locator))407 return True408 else:409 return False410 def clear_input_text_new(self,locator):411 """412 clear the given text field identified by `locator`.413 clear_input_text() does not work if text is right aligned,this new api works.414 """415 self.element = self._element_finder(locator)416 if self.element:417 self.element.send_keys(Keys.CONTROL + "a")418 self.element.send_keys(Keys.DELETE)419 log.mjLog.LogReporter("WebUIOperation","debug","clear_input_text operation \420 successful- %s" %(locator))421 def maximize_browser_window(self):422 """Maximizes the currently opened browser window423 """424 self._current_browser().maximize_window()425 log.mjLog.LogReporter("WebUIOperation","debug","maximize_browser_window - operation successfull")426 427 def minimize_browser_window(self):428 """minimizes the currently opened browser window429 """430 self._current_browser().set_window_position(-2000, 0)431 log.mjLog.LogReporter("WebUIOperation","debug","minimize_browser_window - operation successfull")432 def takeScreenshot(self, funcName, location=None):433 """434 Method to save screen shot to a given path with the function name435 :param funcName: Function name436 :param location: is an optional parameter.If present, the provided location will be used for saving the screen shot437 :return: None438 """439 # trying to figure out the report location440 if location is None:441 for frame in inspect.stack():442 if "page" in frame[1] and "Component" in frame[1]:443 feature_file = frame[1]444 location = feature_file.split("page")[0]445 break446 elif "lib" in frame[1] and "Component" in frame[1]:447 feature_file = frame[1]448 location = feature_file.split("lib")[0]449 break450 else:451 # falling back to framework location452 location = os.path.dirname(os.path.dirname(__file__))453 path = location+"\\reports\\report_"+str(datetime.datetime.now().date())+os.sep454 try:455 if not os.path.exists(path):456 print("Report path not found.Creating...")457 os.makedirs(path)458 name = path+funcName+str(datetime.datetime.now().time()).replace(":","_")+".png"459 print(name)460 self._browser.get_screenshot_as_file(name)461 except Exception, e:462 print(e)463 def sg_get_rows(self, locator):464 """465 returns all the visible rows in a slick grid.466 """467 slick_grid = self._element_finder(locator)468 grid_data = []469 row_data = []470 if self.element:471 rows = slick_grid.find_elements_by_class_name("slick-row")472 for row in rows:473 cells = row.find_elements_by_class_name("slick-cell")474 for cell in cells:475 row_data.append(cell.text)476 grid_data.append(row_data)477 row_data = []478 log.mjLog.LogReporter("WebUIOperation","debug","sg_get_rows operation \479 successful- %s" %(locator))480 return grid_data481 def sg_select_row_containing_text(self, locator, text, all=False):482 """483 text : select a row by clicking on its check box if it has a given text in any of its cells484 all : if true, all rows containing the given text will be selected485 """486 slick_grid = self._element_finder(locator)487 selected = False488 if self.element:489 rows = slick_grid.find_elements_by_class_name("slick-row")490 for row in rows:491 cells = row.find_elements_by_class_name("slick-cell")492 for cell in cells:493 if cell.text == text:494 cells[0].click()495 log.mjLog.LogReporter("WebUIOperation", "debug", "sg_select_row_containing_text operation \496 successful- %s" % (locator))497 selected = True498 break499 if selected and not all:500 break501 if not selected:502 log.mjLog.LogReporter("WebUIOperation", "error", "sg_select_row_containing_text operation \503 unsuccessful- %s" % (locator))504 def sg_select_rows_by_index(self, locator, indexes):505 """506 indexes : list of row index to be selected507 """508 slick_grid = self._element_finder(locator)509 if self.element:510 rows = slick_grid.find_elements_by_class_name("slick-row")511 for index in indexes:512 rows[index].find_elements_by_class_name("slick-cell")[0].click()513 log.mjLog.LogReporter("WebUIOperation", "debug", "sg_select_row_by_index operation successful for index %d" % (index))514 def sg_get_grid_columns_header(self, locator):515 """516 locator : locator for the slick grid517 """518 slick_grid = self._element_finder(locator)519 if self.element:520 headers = slick_grid.find_elements_by_class_name("slick-column-name")521 names = [x.get_attribute('title') for x in headers]522 if len(names):523 log.mjLog.LogReporter("WebUIOperation", "debug", "sg_get_grid_columns_header operation successful")524 return names525 return False526# Private method527 def _element_finder(self, locator, replace_dict=None):528 '''529 _element_finder() - Method to invoke element_finder from browser class530 '''531 return self._browser.element_finder(locator, replace_dict)532 def _elements_finder(self, locator, replace_dict=None):533 '''534 _elements_finder() - Method to invoke elements_finder from browser class535 '''536 return self._browser.elements_finder(locator, replace_dict)537 538 def _map_ascii_key_code_to_key(self, key_code):539 map = {540 "NULL": Keys.NULL,541 "BACKSPACE": Keys.BACK_SPACE,542 "TAB": Keys.TAB,543 "RETURN": Keys.RETURN,544 "ENTER": Keys.ENTER,545 "CANCEL": Keys.CANCEL,546 "ESCAPE": Keys.ESCAPE,547 "SPACE": Keys.SPACE,548 "MULTIPLY": Keys.MULTIPLY,549 "ADD": Keys.ADD,550 "SUBTRACT": Keys.SUBTRACT,551 "DECIMAL": Keys.DECIMAL,552 "DIVIDE": Keys.DIVIDE,553 "SEMICOLON": Keys.SEMICOLON,554 "EQUALS": Keys.EQUALS,555 "SHIFT": Keys.SHIFT,556 "ARROW_UP": Keys.ARROW_UP,557 "ARROW_DOWN": Keys.ARROW_DOWN,558 "ARROW_LEFT": Keys.ARROW_LEFT,559 "ARROW_RIGHT": Keys.ARROW_RIGHT,560 "INSERT": Keys.INSERT,561 "DELETE": Keys.DELETE,562 "END": Keys.END,563 "HOME": Keys.HOME,564 "F12": Keys.F12,565 "ALT": Keys.ALT566 }567 key = map.get(key_code)568 if key is None:569 log.mjLog.LogReporter("WebUIOperation","info","Key not present, returning same string - %s" %(key_code))570 key = chr(key_code)571 return key572 def _alert(self, Cancel=False):573 alert = None574 try:575 576 alert = self._browser.get_current_browser().switch_to_alert()577 text = ' '.join(alert.text.splitlines()) # collapse new lines chars578 if Cancel: alert.dismiss()579 else: alert.accept()580 return text581 except WebDriverException:582 log.mjLog.LogReporter("WebUIOperation","info","Alert not present" )583 return None584 def _current_browser(self):585 return self._browser.get_current_browser()586 587 def _get_list_item_using_text(self, locator, itemtext):588 selectlist=self._element_finder(locator)589 print(selectlist)590 for item in selectlist:591 print(item.text)592 if item.text==itemtext:593 return item594 595 def _get_parent_obj(self, obj):596 return obj.find_element_by_xpath('..')597 598if __name__ == "__main__":599 params = {"name" : "Vinay"}...

Full Screen

Full Screen

mylibrary.py

Source:mylibrary.py Github

copy

Full Screen

...16 for row in reader:17 data.append(row)18 csvfile.close()19 return data20def get_current_browser():21 browser = BuiltIn().get_library_instance('SeleniumLibrary')._current_browser()22 return browser23def get_tittle_via_python():24 driver = get_current_browser()25 title = driver.title26 return title27def click_hirlevel_via_python():28 driver = get_current_browser()29 driver.find_element_by_id('newsletterLink').click()30def szabad_jegyek():31 driver = get_current_browser()32 helyek = driver.find_elements_by_xpath("//*[@status='0']")33 return helyek34def jegy_kijeloles():35 driver = get_current_browser()36 helyek = driver.find_elements_by_xpath("//*[@status='0']")37 webdriver.ActionChains(driver).move_to_element(helyek[0]).click().perform()38def menukattintas():39 driver = get_current_browser()40 helyek = driver.find_element_by_xpath("//mat-option[@id='mat-option-3']")41 webdriver.ActionChains(driver).move_to_element(helyek).click().perform()42def get_time_in_string():43 import datetime44 now = datetime.datetime.now()45 szoveg = now.strftime("%m%d%H%M%S")46 return szoveg47def actionchangesajat(xpath):48 driver = get_current_browser()49 helyek = driver.find_element_by_xpath(xpath)50 webdriver.ActionChains(driver).move_to_element(helyek).click().perform()51def venu_nev():52 driver = get_current_browser()53 venue_lista = driver.find_elements_by_xpath("//boxoffice-sales-product-list-item")54 venunev = venue_lista[0].find_element_by_xpath("//div[@class='title']")55 return venunev.text56def venu_nev2():57 driver = get_current_browser()58 venue_lista = driver.find_elements_by_xpath("//boxoffice-sales-product-list-item")59 venunev = venue_lista[0].find_element_by_xpath("//div[@class='title']")60 return venunev.text61def audit_name():62 driver = get_current_browser()63 venue_lista = driver.find_elements_by_xpath("//boxoffice-sales-product-list-item")64 auditname = venue_lista[0].find_element_by_xpath("//*[@class='auditorium-name']")65 return auditname.text, auditname66def get_parent_child_object(parent_xpath, child_xpath):67 driver = get_current_browser()68 parent = driver.find_elements_by_xpath(parent_xpath)69 child = parent[0].find_element_by_xpath(child_xpath)70 return child71def get_child_object(parent, child_xpath):72 driver = get_current_browser()73 child = parent.find_element_by_xpath(child_xpath)74 return child75def check_the_elem_contain_in_parent(parent, child_xpath):76 driver = get_current_browser()77 child = parent.find_element_by_xpath(child_xpath)78 return child79def check_the_elem_contain_in_parent2(parent, child_xpath):80 driver = get_current_browser()81 try:82 child = parent.find_element_by_xpath(child_xpath)83 visszaad = True84 except:85 visszaad = False86 finally:87 if visszaad==False:88 child = None89 return visszaad, child90def date_string_hu_to_date(datestring):91 import locale92 from datetime import date, datetime, time93 # locale.setlocale(locale.LC_ALL, 'hu_HU')94 eredmeny = True95 dateobject = datetime.strptime('2019. január 30., szerda', "%Y. %B %d., %A")96 try:97 print('valami')98 dateobject = datetime.strptime(datestring, "%Y. %B %d., %A")99 except:100 eredmeny = False101 return eredmeny102def return_date_text(text_date):103 from datetime import date, datetime, time104 from babel.dates import format_date, format_datetime, format_time105 honapok = {'január': 1, 'február': 2, 'március': 3, 'április': 4, 'május': 5, 'június': 6, 'július': 7, 'augusztus': 8, 'szeptember': 9, 'október': 10, 'november': 11, 'december': 12}106 cut_string = text_date.split(' ')107 honap = cut_string[1]108 nap = cut_string[2].split('.')109 evs = cut_string[0][0:4]110 honapszama = honapok[honap]111 naps = nap[0]112 d = date(int(evs), honapszama, int(naps))113 return format_date(d, format='full', locale='hu')114def elem_keresese(elemkeres):115 driver = get_current_browser()116 #helyek = driver.find_element_by_class_name(elemkeres)117 helyek = driver.find_element_by_css_selector(elemkeres)118 #return helyek119def string_of_other_string(string, start, end):120 start2 = int(start)121 end2 = int(end)122 szoveg = string[start2:end2]123 return szoveg124def check_the_page_finish_loaded():125 import datetime126 import time127 #driver = get_current_browser()128 starttime = datetime.datetime.now()129 timeout = False130 if driver.execute_script('return document.readyState;') == 'complete':131 betoltve = True132 print("elso betöltes sikeres")133 else:134 betoltve = False135 while (betoltve==False) and (timeout==False):136 time.sleep(0.2)137 if driver.execute_script('return document.readyState;') == 'complete':138 betoltve = True139 #print("betoltes vege")140 else:141 most = datetime.datetime.now()...

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 robotframework-pageobjects 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