Best Python code snippet using SeleniumBase
base_case.py
Source:base_case.py
...80 """ This method clicks link text on a page """81 # If using phantomjs, might need to extract and open the link directly82 if self.browser == 'phantomjs':83 if self.is_link_text_visible(link_text):84 element = self.wait_for_link_text_visible(link_text)85 element.click()86 return87 source = self.driver.page_source88 soup = BeautifulSoup(source)89 html_links = soup.fetch('a')90 for html_link in html_links:91 if html_link.text == link_text:92 for html_attribute in html_link.attrs:93 if html_attribute[0] == 'href':94 href = html_attribute[1]95 if href.startswith('//'):96 link = "http:" + href97 elif href.startswith('/'):98 url = self.driver.current_url99 domain_url = self.get_domain_url(url)100 link = domain_url + href101 else:102 link = href103 self.open(link)104 return105 raise Exception(106 'Could not parse link from link_text [%s]' % link_text)107 raise Exception("Link text [%s] was not found!" % link_text)108 # Not using phantomjs109 element = self.wait_for_link_text_visible(link_text, timeout=timeout)110 self._demo_mode_highlight_if_active(link_text, by=By.LINK_TEXT)111 pre_action_url = self.driver.current_url112 element.click()113 if settings.WAIT_FOR_RSC_ON_CLICKS:114 self.wait_for_ready_state_complete()115 if self.demo_mode:116 if self.driver.current_url != pre_action_url:117 self._demo_mode_pause_if_active()118 else:119 self._demo_mode_pause_if_active(tiny=True)120 def get_text(self, selector, by=By.CSS_SELECTOR,121 timeout=settings.SMALL_TIMEOUT):122 element = page_actions.wait_for_element_visible(123 self.driver, selector, by, timeout)124 return element.text125 def get_attribute(self, selector, attribute, by=By.CSS_SELECTOR,126 timeout=settings.SMALL_TIMEOUT):127 element = page_actions.wait_for_element_present(128 self.driver, selector, by, timeout)129 attribute_value = element.get_attribute(attribute)130 if attribute_value is not None:131 return attribute_value132 else:133 raise Exception("Element [%s] has no attribute [%s]!" % (134 selector, attribute))135 def add_text(self, selector, new_value, by=By.CSS_SELECTOR,136 timeout=settings.SMALL_TIMEOUT):137 """ The more-reliable version of driver.send_keys()138 Similar to update_text(), but won't clear the text field first. """139 element = self.wait_for_element_visible(140 selector, by=by, timeout=timeout)141 self._demo_mode_highlight_if_active(selector, by)142 pre_action_url = self.driver.current_url143 element.send_keys(new_value)144 if self.demo_mode:145 if self.driver.current_url != pre_action_url:146 self._demo_mode_pause_if_active()147 else:148 self._demo_mode_pause_if_active(tiny=True)149 def send_keys(self, selector, new_value, by=By.CSS_SELECTOR,150 timeout=settings.SMALL_TIMEOUT):151 """ Same as add_text() -> more reliable, but less name confusion. """152 self.add_text(selector, new_value, by=by, timeout=timeout)153 def update_text_value(self, selector, new_value, by=By.CSS_SELECTOR,154 timeout=settings.SMALL_TIMEOUT, retry=False):155 """ This method updates an element's text value with a new value.156 @Params157 selector - the selector with the value to update158 new_value - the new value for setting the text field159 by - the type of selector to search by (Default: CSS)160 timeout - how long to wait for the selector to be visible161 retry - if True, use jquery if the selenium text update fails162 """163 element = self.wait_for_element_visible(164 selector, by=by, timeout=timeout)165 self._demo_mode_highlight_if_active(selector, by)166 element.clear()167 self._demo_mode_pause_if_active(tiny=True)168 pre_action_url = self.driver.current_url169 element.send_keys(new_value)170 if (retry and element.get_attribute('value') != new_value and (171 not new_value.endswith('\n'))):172 logging.debug('update_text_value is falling back to jQuery!')173 selector = self.jq_format(selector)174 self.set_value(selector, new_value, by=by)175 if self.demo_mode:176 if self.driver.current_url != pre_action_url:177 self._demo_mode_pause_if_active()178 else:179 self._demo_mode_pause_if_active(tiny=True)180 def update_text(self, selector, new_value, by=By.CSS_SELECTOR,181 timeout=settings.SMALL_TIMEOUT, retry=False):182 """ The shorter version of update_text_value(), which183 clears existing text and adds new text into the text field.184 We want to keep the old version for backward compatibility. """185 self.update_text_value(selector, new_value, by=by,186 timeout=timeout, retry=retry)187 def is_element_present(self, selector, by=By.CSS_SELECTOR):188 if selector.startswith('/') or selector.startswith('./'):189 by = By.XPATH190 return page_actions.is_element_present(self.driver, selector, by)191 def is_element_visible(self, selector, by=By.CSS_SELECTOR):192 if selector.startswith('/') or selector.startswith('./'):193 by = By.XPATH194 return page_actions.is_element_visible(self.driver, selector, by)195 def is_link_text_visible(self, link_text):196 return page_actions.is_element_visible(self.driver, link_text,197 by=By.LINK_TEXT)198 def is_text_visible(self, text, selector, by=By.CSS_SELECTOR):199 if selector.startswith('/') or selector.startswith('./'):200 by = By.XPATH201 return page_actions.is_text_visible(self.driver, text, selector, by)202 def find_visible_elements(self, selector, by=By.CSS_SELECTOR):203 if selector.startswith('/') or selector.startswith('./'):204 by = By.XPATH205 return page_actions.find_visible_elements(self.driver, selector, by)206 def execute_script(self, script):207 return self.driver.execute_script(script)208 def set_window_size(self, width, height):209 return self.driver.set_window_size(width, height)210 self._demo_mode_pause_if_active()211 def maximize_window(self):212 return self.driver.maximize_window()213 self._demo_mode_pause_if_active()214 def activate_jquery(self):215 """ If "jQuery is not defined", use this method to activate it for use.216 This happens because jQuery is not always defined on web sites. """217 try:218 # Let's first find out if jQuery is already defined.219 self.execute_script("jQuery('html')")220 # Since that command worked, jQuery is defined. Let's return.221 return222 except Exception:223 # jQuery is not currently defined. Let's proceed by defining it.224 pass225 self.execute_script(226 '''var script = document.createElement("script"); '''227 '''script.src = "http://code.jquery.com/jquery-2.2.4.min.js"; '''228 '''document.getElementsByTagName("head")[0]'''229 '''.appendChild(script);''')230 for x in xrange(30):231 # jQuery needs a small amount of time to activate. (At most 3s)232 try:233 self.execute_script("jQuery('html')")234 return235 except Exception:236 time.sleep(0.1)237 # Since jQuery still isn't activating, give up and raise an exception238 raise Exception("Exception: WebDriver could not activate jQuery!")239 def highlight(self, selector, by=By.CSS_SELECTOR,240 loops=settings.HIGHLIGHTS, scroll=True):241 """ This method uses fancy javascript to highlight an element.242 Used during demo_mode.243 @Params244 selector - the selector of the element to find245 by - the type of selector to search by (Default: CSS)246 loops - # of times to repeat the highlight animation247 (Default: 4. Each loop lasts for about 0.18s)248 scroll - the option to scroll to the element first (Default: True)249 """250 element = self.find_element(251 selector, by=by, timeout=settings.SMALL_TIMEOUT)252 if scroll:253 self._slow_scroll_to_element(element)254 try:255 selector = self.convert_to_css_selector(selector, by=by)256 except Exception:257 # Don't highlight if can't convert to CSS_SELECTOR for jQuery258 return259 # Only get the first match260 last_syllable = selector.split(' ')[-1]261 if ':' not in last_syllable:262 selector += ':first'263 o_bs = '' # original_box_shadow264 style = element.get_attribute('style')265 if style:266 if 'box-shadow: ' in style:267 box_start = style.find('box-shadow: ')268 box_end = style.find(';', box_start) + 1269 original_box_shadow = style[box_start:box_end]270 o_bs = original_box_shadow271 script = """jQuery('%s').css('box-shadow',272 '0px 0px 6px 6px rgba(128, 128, 128, 0.5)');""" % selector273 try:274 self.execute_script(script)275 except Exception:276 self.activate_jquery()277 self.execute_script(script)278 if self.highlights:279 loops = self.highlights280 loops = int(loops)281 for n in xrange(loops):282 script = """jQuery('%s').css('box-shadow',283 '0px 0px 6px 6px rgba(255, 0, 0, 1)');""" % selector284 self.execute_script(script)285 time.sleep(0.02)286 script = """jQuery('%s').css('box-shadow',287 '0px 0px 6px 6px rgba(128, 0, 128, 1)');""" % selector288 self.execute_script(script)289 time.sleep(0.02)290 script = """jQuery('%s').css('box-shadow',291 '0px 0px 6px 6px rgba(0, 0, 255, 1)');""" % selector292 self.execute_script(script)293 time.sleep(0.02)294 script = """jQuery('%s').css('box-shadow',295 '0px 0px 6px 6px rgba(0, 255, 0, 1)');""" % selector296 self.execute_script(script)297 time.sleep(0.02)298 script = """jQuery('%s').css('box-shadow',299 '0px 0px 6px 6px rgba(128, 128, 0, 1)');""" % selector300 self.execute_script(script)301 time.sleep(0.02)302 script = """jQuery('%s').css('box-shadow',303 '0px 0px 6px 6px rgba(128, 0, 128, 1)');""" % selector304 self.execute_script(script)305 time.sleep(0.02)306 script = """jQuery('%s').css('box-shadow', '%s');""" % (selector, o_bs)307 self.execute_script(script)308 time.sleep(0.065)309 def scroll_to(self, selector, by=By.CSS_SELECTOR,310 timeout=settings.SMALL_TIMEOUT):311 ''' Fast scroll to destination '''312 element = self.wait_for_element_visible(313 selector, by=by, timeout=timeout)314 self._scroll_to_element(element)315 def slow_scroll_to(self, selector, by=By.CSS_SELECTOR,316 timeout=settings.SMALL_TIMEOUT):317 ''' Slow motion scroll to destination '''318 element = self.wait_for_element_visible(319 selector, by=by, timeout=timeout)320 self._slow_scroll_to_element(element)321 def scroll_click(self, selector, by=By.CSS_SELECTOR):322 self.scroll_to(selector, by=by)323 self.click(selector, by=by)324 def jquery_click(self, selector, by=By.CSS_SELECTOR):325 if selector.startswith('/') or selector.startswith('./'):326 by = By.XPATH327 selector = self.convert_to_css_selector(selector, by=by)328 self.wait_for_element_present(329 selector, by=by, timeout=settings.SMALL_TIMEOUT)330 if self.is_element_visible(selector, by=by):331 self._demo_mode_highlight_if_active(selector, by)332 # Only get the first match333 last_syllable = selector.split(' ')[-1]334 if ':' not in last_syllable:335 selector += ':first'336 click_script = """jQuery('%s')[0].click()""" % selector337 try:338 self.execute_script(click_script)339 except Exception:340 # The likely reason this fails is because: "jQuery is not defined"341 self.activate_jquery() # It's a good thing we can define it here342 self.execute_script(click_script)343 self._demo_mode_pause_if_active()344 def jq_format(self, code):345 return page_utils.jq_format(code)346 def get_domain_url(self, url):347 return page_utils.get_domain_url(url)348 def download_file(self, file_url, destination_folder=None):349 """ Downloads the file from the url to the destination folder.350 If no destination folder is specified, the default one is used. """351 if not destination_folder:352 destination_folder = constants.Files.DOWNLOADS_FOLDER353 page_utils._download_file_to(file_url, destination_folder)354 return True355 def save_file_as(self, file_url, new_file_name, destination_folder=None):356 """ Similar to self.download_file(), except that you get to rename the357 file being downloaded to whatever you want. """358 if not destination_folder:359 destination_folder = constants.Files.DOWNLOADS_FOLDER360 page_utils._download_file_to(361 file_url, destination_folder, new_file_name)362 return True363 def convert_xpath_to_css(self, xpath):364 return xpath_to_css.convert_xpath_to_css(xpath)365 def convert_to_css_selector(self, selector, by):366 """ This method converts a selector to a CSS_SELECTOR.367 jQuery commands require a CSS_SELECTOR for finding elements.368 This method should only be used for jQuery actions. """369 if by == By.CSS_SELECTOR:370 return selector371 elif by == By.ID:372 return '#%s' % selector373 elif by == By.CLASS_NAME:374 return '.%s' % selector375 elif by == By.NAME:376 return '[name="%s"]' % selector377 elif by == By.TAG_NAME:378 return selector379 elif by == By.XPATH:380 return self.convert_xpath_to_css(selector)381 elif by == By.LINK_TEXT:382 return 'a:contains("%s")' % selector383 elif by == By.PARTIAL_LINK_TEXT:384 return 'a:contains("%s")' % selector385 else:386 raise Exception(387 "Exception: Could not convert [%s](by=%s) to CSS_SELECTOR!" % (388 selector, by))389 def set_value(self, selector, new_value, by=By.CSS_SELECTOR,390 timeout=settings.SMALL_TIMEOUT):391 """ This method uses jQuery to update a text field. """392 if selector.startswith('/') or selector.startswith('./'):393 by = By.XPATH394 selector = self.convert_to_css_selector(selector, by=by)395 self._demo_mode_highlight_if_active(selector, by)396 self.scroll_to(selector, by=by, timeout=timeout)397 value = json.dumps(new_value)398 # Only get the first match399 last_syllable = selector.split(' ')[-1]400 if ':' not in last_syllable:401 selector += ':first'402 set_value_script = """jQuery('%s').val(%s)""" % (selector, value)403 try:404 self.execute_script(set_value_script)405 except Exception:406 # The likely reason this fails is because: "jQuery is not defined"407 self.activate_jquery() # It's a good thing we can define it here408 self.execute_script(set_value_script)409 self._demo_mode_pause_if_active()410 def jquery_update_text_value(self, selector, new_value, by=By.CSS_SELECTOR,411 timeout=settings.SMALL_TIMEOUT):412 """ This method uses jQuery to update a text field.413 If the new_value string ends with the newline character,414 WebDriver will finish the call, which simulates pressing415 {Enter/Return} after the text is entered. """416 if selector.startswith('/') or selector.startswith('./'):417 by = By.XPATH418 element = self.wait_for_element_visible(419 selector, by=by, timeout=timeout)420 self._demo_mode_highlight_if_active(selector, by)421 self.scroll_to(selector, by=by)422 selector = self.convert_to_css_selector(selector, by=by)423 # Only get the first match424 last_syllable = selector.split(' ')[-1]425 if ':' not in last_syllable:426 selector += ':first'427 update_text_script = """jQuery('%s').val('%s')""" % (428 selector, self.jq_format(new_value))429 try:430 self.execute_script(update_text_script)431 except Exception:432 # The likely reason this fails is because: "jQuery is not defined"433 self.activate_jquery() # It's a good thing we can define it here434 self.execute_script(update_text_script)435 if new_value.endswith('\n'):436 element.send_keys('\n')437 self._demo_mode_pause_if_active()438 def jquery_update_text(self, selector, new_value, by=By.CSS_SELECTOR,439 timeout=settings.SMALL_TIMEOUT):440 """ The shorter version of jquery_update_text_value()441 (The longer version remains for backwards compatibility.) """442 self.jquery_update_text_value(443 selector, new_value, by=by, timeout=timeout)444 def hover_on_element(self, selector, by=By.CSS_SELECTOR):445 self.wait_for_element_visible(446 selector, by=by, timeout=settings.SMALL_TIMEOUT)447 self._demo_mode_highlight_if_active(selector, by)448 self.scroll_to(selector, by=by)449 time.sleep(0.05) # Settle down from scrolling before hovering450 return page_actions.hover_on_element(self.driver, selector)451 def hover_and_click(self, hover_selector, click_selector,452 hover_by=By.CSS_SELECTOR, click_by=By.CSS_SELECTOR,453 timeout=settings.SMALL_TIMEOUT):454 if hover_selector.startswith('/') or hover_selector.startswith('./'):455 hover_by = By.XPATH456 if click_selector.startswith('/') or click_selector.startswith('./'):457 click_by = By.XPATH458 self.wait_for_element_visible(459 hover_selector, by=hover_by, timeout=timeout)460 self._demo_mode_highlight_if_active(hover_selector, hover_by)461 self.scroll_to(hover_selector, by=hover_by)462 pre_action_url = self.driver.current_url463 element = page_actions.hover_and_click(464 self.driver, hover_selector, click_selector,465 hover_by, click_by, timeout)466 if self.demo_mode:467 if self.driver.current_url != pre_action_url:468 self._demo_mode_pause_if_active()469 else:470 self._demo_mode_pause_if_active(tiny=True)471 return element472 ############473 def wait_for_element_present(self, selector, by=By.CSS_SELECTOR,474 timeout=settings.LARGE_TIMEOUT):475 """ Waits for an element to appear in the HTML of a page.476 The element does not need be visible (it may be hidden). """477 if selector.startswith('/') or selector.startswith('./'):478 by = By.XPATH479 return page_actions.wait_for_element_present(480 self.driver, selector, by, timeout)481 def assert_element_present(self, selector, by=By.CSS_SELECTOR,482 timeout=settings.SMALL_TIMEOUT):483 """ Similar to wait_for_element_present(), but returns nothing.484 Waits for an element to appear in the HTML of a page.485 The element does not need be visible (it may be hidden).486 Returns True if successful. Default timeout = SMALL_TIMEOUT. """487 self.wait_for_element_present(selector, by=by, timeout=timeout)488 return True489 # For backwards compatibility, earlier method names of the next490 # four methods have remained even though they do the same thing,491 # with the exception of assert_*, which won't return the element,492 # but like the others, will raise an exception if the call fails.493 def wait_for_element_visible(self, selector, by=By.CSS_SELECTOR,494 timeout=settings.LARGE_TIMEOUT):495 """ Waits for an element to appear in the HTML of a page.496 The element must be visible (it cannot be hidden). """497 if selector.startswith('/') or selector.startswith('./'):498 by = By.XPATH499 return page_actions.wait_for_element_visible(500 self.driver, selector, by, timeout)501 def wait_for_element(self, selector, by=By.CSS_SELECTOR,502 timeout=settings.LARGE_TIMEOUT):503 """ The shorter version of wait_for_element_visible() """504 return self.wait_for_element_visible(selector, by=by, timeout=timeout)505 def find_element(self, selector, by=By.CSS_SELECTOR,506 timeout=settings.LARGE_TIMEOUT):507 """ Same as wait_for_element_visible() - returns the element """508 return self.wait_for_element_visible(selector, by=by, timeout=timeout)509 def assert_element(self, selector, by=By.CSS_SELECTOR,510 timeout=settings.SMALL_TIMEOUT):511 """ Similar to wait_for_element_visible(), but returns nothing.512 As above, will raise an exception if nothing can be found.513 Returns True if successful. Default timeout = SMALL_TIMEOUT. """514 self.wait_for_element_visible(selector, by=by, timeout=timeout)515 return True516 # For backwards compatibility, earlier method names of the next517 # four methods have remained even though they do the same thing,518 # with the exception of assert_*, which won't return the element,519 # but like the others, will raise an exception if the call fails.520 def wait_for_text_visible(self, text, selector, by=By.CSS_SELECTOR,521 timeout=settings.LARGE_TIMEOUT):522 if selector.startswith('/') or selector.startswith('./'):523 by = By.XPATH524 return page_actions.wait_for_text_visible(525 self.driver, text, selector, by, timeout)526 def wait_for_text(self, text, selector, by=By.CSS_SELECTOR,527 timeout=settings.LARGE_TIMEOUT):528 """ The shorter version of wait_for_text_visible() """529 return self.wait_for_text_visible(530 text, selector, by=by, timeout=timeout)531 def find_text(self, text, selector, by=By.CSS_SELECTOR,532 timeout=settings.LARGE_TIMEOUT):533 """ Same as wait_for_text_visible() - returns the element """534 return self.wait_for_text_visible(535 text, selector, by=by, timeout=timeout)536 def assert_text(self, text, selector, by=By.CSS_SELECTOR,537 timeout=settings.SMALL_TIMEOUT):538 """ Similar to wait_for_text_visible(), but returns nothing.539 As above, will raise an exception if nothing can be found.540 Returns True if successful. Default timeout = SMALL_TIMEOUT. """541 self.wait_for_text_visible(text, selector, by=by, timeout=timeout)542 return True543 # For backwards compatibility, earlier method names of the next544 # four methods have remained even though they do the same thing,545 # with the exception of assert_*, which won't return the element,546 # but like the others, will raise an exception if the call fails.547 def wait_for_link_text_visible(self, link_text,548 timeout=settings.LARGE_TIMEOUT):549 return self.wait_for_element_visible(550 link_text, by=By.LINK_TEXT, timeout=timeout)551 def wait_for_link_text(self, link_text, timeout=settings.LARGE_TIMEOUT):552 """ The shorter version of wait_for_link_text_visible() """553 return self.wait_for_link_text_visible(link_text, timeout=timeout)554 def find_link_text(self, link_text, timeout=settings.LARGE_TIMEOUT):555 """ Same as wait_for_link_text_visible() - returns the element """556 return self.wait_for_link_text_visible(link_text, timeout=timeout)557 def assert_link_text(self, link_text, timeout=settings.SMALL_TIMEOUT):558 """ Similar to wait_for_link_text_visible(), but returns nothing.559 As above, will raise an exception if nothing can be found.560 Returns True if successful. Default timeout = SMALL_TIMEOUT. """561 self.wait_for_link_text_visible(link_text, timeout=timeout)562 return True563 ############564 def wait_for_element_absent(self, selector, by=By.CSS_SELECTOR,565 timeout=settings.LARGE_TIMEOUT):566 """ Waits for an element to no longer appear in the HTML of a page.567 A hidden element still counts as appearing in the page HTML.568 If an element with "hidden" status is acceptable,569 use wait_for_element_not_visible() instead. """570 if selector.startswith('/') or selector.startswith('./'):571 by = By.XPATH572 return page_actions.wait_for_element_absent(573 self.driver, selector, by, timeout)574 def assert_element_absent(self, selector, by=By.CSS_SELECTOR,575 timeout=settings.SMALL_TIMEOUT):...
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!