Best Python code snippet using SeleniumBase
tour_helper.py
Source:tour_helper.py
...25 js_utils.add_css_style(driver, backdrop_style)26 js_utils.wait_for_ready_state_complete(driver)27 js_utils.wait_for_angularjs(driver)28 for x in range(4):29 js_utils.activate_jquery(driver)30 js_utils.add_css_link(driver, bootstrap_tour_css)31 js_utils.add_js_link(driver, bootstrap_tour_js)32 time.sleep(0.1)33 for x in range(int(settings.MINI_TIMEOUT * 2.0)):34 # Bootstrap needs a small amount of time to load & activate.35 try:36 driver.execute_script(verify_script)37 time.sleep(0.05)38 return39 except Exception:40 time.sleep(0.15)41 js_utils.raise_unable_to_load_jquery_exception(driver)42def is_bootstrap_activated(driver):43 verify_script = ("""// Verify Bootstrap Tour activated44 var tour2 = new Tour({45 });""")46 try:47 driver.execute_script(verify_script)48 return True49 except Exception:50 return False51def activate_driverjs(driver):52 """ Allows you to use DriverJS Tours with SeleniumBase53 https://kamranahmed.info/driver.js/54 """55 backdrop_style = style_sheet.dt_backdrop_style56 driverjs_css = constants.DriverJS.MIN_CSS57 driverjs_js = constants.DriverJS.MIN_JS58 verify_script = ("""// Verify DriverJS activated59 var driverjs2 = Driver.name;60 """)61 activate_bootstrap(driver)62 js_utils.wait_for_ready_state_complete(driver)63 js_utils.wait_for_angularjs(driver)64 js_utils.add_css_style(driver, backdrop_style)65 for x in range(4):66 js_utils.activate_jquery(driver)67 js_utils.add_css_link(driver, driverjs_css)68 js_utils.add_js_link(driver, driverjs_js)69 time.sleep(0.1)70 for x in range(int(settings.MINI_TIMEOUT * 2.0)):71 # DriverJS needs a small amount of time to load & activate.72 try:73 driver.execute_script(verify_script)74 js_utils.wait_for_ready_state_complete(driver)75 js_utils.wait_for_angularjs(driver)76 time.sleep(0.05)77 return78 except Exception:79 time.sleep(0.15)80 js_utils.raise_unable_to_load_jquery_exception(driver)81def is_driverjs_activated(driver):82 verify_script = ("""// Verify DriverJS activated83 var driverjs2 = Driver.name;84 """)85 try:86 driver.execute_script(verify_script)87 return True88 except Exception:89 return False90def activate_hopscotch(driver):91 """ Allows you to use Hopscotch Tours with SeleniumBase92 http://linkedin.github.io/hopscotch/93 """94 hopscotch_css = constants.Hopscotch.MIN_CSS95 hopscotch_js = constants.Hopscotch.MIN_JS96 backdrop_style = style_sheet.hops_backdrop_style97 verify_script = ("""// Verify Hopscotch activated98 var hops = hopscotch.isActive;99 """)100 activate_bootstrap(driver)101 js_utils.wait_for_ready_state_complete(driver)102 js_utils.wait_for_angularjs(driver)103 js_utils.add_css_style(driver, backdrop_style)104 for x in range(4):105 js_utils.activate_jquery(driver)106 js_utils.add_css_link(driver, hopscotch_css)107 js_utils.add_js_link(driver, hopscotch_js)108 time.sleep(0.1)109 for x in range(int(settings.MINI_TIMEOUT * 2.0)):110 # Hopscotch needs a small amount of time to load & activate.111 try:112 driver.execute_script(verify_script)113 js_utils.wait_for_ready_state_complete(driver)114 js_utils.wait_for_angularjs(driver)115 time.sleep(0.05)116 return117 except Exception:118 time.sleep(0.15)119 js_utils.raise_unable_to_load_jquery_exception(driver)120def is_hopscotch_activated(driver):121 verify_script = ("""// Verify Hopscotch activated122 var hops = hopscotch.isActive;123 """)124 try:125 driver.execute_script(verify_script)126 return True127 except Exception:128 return False129def activate_introjs(driver):130 """ Allows you to use IntroJS Tours with SeleniumBase131 https://introjs.com/132 """133 intro_css = constants.IntroJS.MIN_CSS134 intro_js = constants.IntroJS.MIN_JS135 verify_script = ("""// Verify IntroJS activated136 var intro2 = introJs();137 """)138 activate_bootstrap(driver)139 js_utils.wait_for_ready_state_complete(driver)140 js_utils.wait_for_angularjs(driver)141 for x in range(4):142 js_utils.activate_jquery(driver)143 js_utils.add_css_link(driver, intro_css)144 js_utils.add_js_link(driver, intro_js)145 time.sleep(0.1)146 for x in range(int(settings.MINI_TIMEOUT * 2.0)):147 # IntroJS needs a small amount of time to load & activate.148 try:149 driver.execute_script(verify_script)150 js_utils.wait_for_ready_state_complete(driver)151 js_utils.wait_for_angularjs(driver)152 time.sleep(0.05)153 return154 except Exception:155 time.sleep(0.15)156 js_utils.raise_unable_to_load_jquery_exception(driver)...
js_utils.py
Source:js_utils.py
...131 """Unable to load jQuery on "%s" because this website """132 """restricts external JavaScript resources from loading."""133 % driver.current_url134 )135def activate_jquery(driver):136 """If "jQuery is not defined", use this method to activate it for use.137 This happens because jQuery is not always defined on web sites."""138 try:139 # Let's first find out if jQuery is already defined.140 driver.execute_script("jQuery('html');")141 # Since that command worked, jQuery is defined. Let's return.142 return143 except Exception:144 # jQuery is not currently defined. Let's proceed by defining it.145 pass146 jquery_js = constants.JQuery.MIN_JS147 add_js_link(driver, jquery_js)148 for x in range(int(settings.MINI_TIMEOUT * 10.0)):149 # jQuery needs a small amount of time to activate.150 try:151 driver.execute_script("jQuery('html');")152 return153 except Exception:154 time.sleep(0.1)155 try:156 add_js_link(driver, jquery_js)157 time.sleep(0.1)158 driver.execute_script("jQuery('head');")159 except Exception:160 pass161 # Since jQuery still isn't activating, give up and raise an exception162 raise_unable_to_load_jquery_exception(driver)163def are_quotes_escaped(string):164 if string.count("\\'") != string.count("'") or (165 string.count('\\"') != string.count('"')166 ):167 return True168 return False169def escape_quotes_if_needed(string):170 """171 re.escape() works differently in Python 3.7.0 than earlier versions:172 Python 3.6.5:173 >>> import re174 >>> re.escape('"')175 '\\"'176 Python 3.7.0:177 >>> import re178 >>> re.escape('"')179 '"'180 SeleniumBase needs quotes to be properly escaped for Javascript calls.181 """182 if are_quotes_escaped(string):183 if string.count("'") != string.count("\\'"):184 string = string.replace("'", "\\'")185 if string.count('"') != string.count('\\"'):186 string = string.replace('"', '\\"')187 return string188def is_in_frame(driver):189 """190 Returns True if the driver has switched to a frame.191 Returns False if the driver was on default content.192 """193 in_basic_frame = driver.execute_script(194 """195 var frame = window.frameElement;196 if (frame) {197 return true;198 }199 else {200 return false;201 }202 """203 )204 location_href = driver.execute_script("""return window.location.href;""")205 in_external_frame = False206 if driver.current_url != location_href:207 in_external_frame = True208 if in_basic_frame or in_external_frame:209 return True210 return False211def safe_execute_script(driver, script):212 """When executing a script that contains a jQuery command,213 it's important that the jQuery library has been loaded first.214 This method will load jQuery if it wasn't already loaded."""215 try:216 driver.execute_script(script)217 except Exception:218 # The likely reason this fails is because: "jQuery is not defined"219 activate_jquery(driver) # It's a good thing we can define it here220 driver.execute_script(script)221def wait_for_css_query_selector(222 driver, selector, timeout=settings.SMALL_TIMEOUT223):224 element = None225 start_ms = time.time() * 1000.0226 stop_ms = start_ms + (timeout * 1000.0)227 for x in range(int(timeout * 10)):228 try:229 selector = re.escape(selector)230 selector = escape_quotes_if_needed(selector)231 element = driver.execute_script(232 """return document.querySelector('%s')""" % selector233 )234 if element:235 return element236 except Exception:237 element = None238 if not element:239 now_ms = time.time() * 1000.0240 if now_ms >= stop_ms:241 break242 time.sleep(0.1)243 raise NoSuchElementException(244 "Element {%s} was not present after %s seconds!" % (selector, timeout)245 )246def highlight_with_js(driver, selector, loops, o_bs):247 try:248 # This closes any pop-up alerts249 driver.execute_script("")250 except Exception:251 pass252 if selector == "html":253 selector = "body"254 selector_no_spaces = selector.replace(" ", "")255 early_exit = False256 if '[style=\\"' in selector_no_spaces:257 if 'box\\-shadow:' in selector:258 early_exit = True # Changing the box-shadow changes the selector259 elif '[style=\\"' in selector:260 selector = selector.replace('[style=\\"', '[style\\*=\\"')261 else:262 early_exit = True # Changing the box-shadow changes the selector263 if early_exit:264 return265 script = (266 """document.querySelector('%s').style.boxShadow =267 '0px 0px 6px 6px rgba(128, 128, 128, 0.5)';"""268 % selector269 )270 try:271 driver.execute_script(script)272 except Exception:273 return274 for n in range(loops):275 script = (276 """document.querySelector('%s').style.boxShadow =277 '0px 0px 6px 6px rgba(255, 0, 0, 1)';"""278 % selector279 )280 try:281 driver.execute_script(script)282 except Exception:283 return284 time.sleep(0.0181)285 script = (286 """document.querySelector('%s').style.boxShadow =287 '0px 0px 6px 6px rgba(128, 0, 128, 1)';"""288 % selector289 )290 try:291 driver.execute_script(script)292 except Exception:293 return294 time.sleep(0.0181)295 script = (296 """document.querySelector('%s').style.boxShadow =297 '0px 0px 6px 6px rgba(0, 0, 255, 1)';"""298 % selector299 )300 try:301 driver.execute_script(script)302 except Exception:303 return304 time.sleep(0.0181)305 script = (306 """document.querySelector('%s').style.boxShadow =307 '0px 0px 6px 6px rgba(0, 255, 0, 1)';"""308 % selector309 )310 try:311 driver.execute_script(script)312 except Exception:313 return314 time.sleep(0.0181)315 script = (316 """document.querySelector('%s').style.boxShadow =317 '0px 0px 6px 6px rgba(128, 128, 0, 1)';"""318 % selector319 )320 try:321 driver.execute_script(script)322 except Exception:323 return324 time.sleep(0.0181)325 script = (326 """document.querySelector('%s').style.boxShadow =327 '0px 0px 6px 6px rgba(128, 0, 128, 1)';"""328 % selector329 )330 try:331 driver.execute_script(script)332 except Exception:333 return334 time.sleep(0.0181)335 script = """document.querySelector('%s').style.boxShadow =336 '%s';""" % (337 selector,338 o_bs,339 )340 try:341 driver.execute_script(script)342 except Exception:343 return344def highlight_with_jquery(driver, selector, loops, o_bs):345 try:346 # This closes any pop-up alerts347 driver.execute_script("")348 except Exception:349 pass350 if selector == "html":351 selector = "body"352 selector_no_spaces = selector.replace(" ", "")353 early_exit = False354 if '[style=\\"' in selector_no_spaces:355 if 'box\\-shadow:' in selector:356 early_exit = True # Changing the box-shadow changes the selector357 elif '[style=\\"' in selector:358 selector = selector.replace('[style=\\"', '[style\\*=\\"')359 else:360 early_exit = True # Changing the box-shadow changes the selector361 if early_exit:362 return363 script = (364 """jQuery('%s').css('box-shadow',365 '0px 0px 6px 6px rgba(128, 128, 128, 0.5)');"""366 % selector367 )368 safe_execute_script(driver, script)369 for n in range(loops):370 script = (371 """jQuery('%s').css('box-shadow',372 '0px 0px 6px 6px rgba(255, 0, 0, 1)');"""373 % selector374 )375 driver.execute_script(script)376 time.sleep(0.0181)377 script = (378 """jQuery('%s').css('box-shadow',379 '0px 0px 6px 6px rgba(128, 0, 128, 1)');"""380 % selector381 )382 driver.execute_script(script)383 time.sleep(0.0181)384 script = (385 """jQuery('%s').css('box-shadow',386 '0px 0px 6px 6px rgba(0, 0, 255, 1)');"""387 % selector388 )389 driver.execute_script(script)390 time.sleep(0.0181)391 script = (392 """jQuery('%s').css('box-shadow',393 '0px 0px 6px 6px rgba(0, 255, 0, 1)');"""394 % selector395 )396 driver.execute_script(script)397 time.sleep(0.0181)398 script = (399 """jQuery('%s').css('box-shadow',400 '0px 0px 6px 6px rgba(128, 128, 0, 1)');"""401 % selector402 )403 driver.execute_script(script)404 time.sleep(0.0181)405 script = (406 """jQuery('%s').css('box-shadow',407 '0px 0px 6px 6px rgba(128, 0, 128, 1)');"""408 % selector409 )410 driver.execute_script(script)411 time.sleep(0.0181)412 script = """jQuery('%s').css('box-shadow', '%s');""" % (selector, o_bs)413 driver.execute_script(script)414def add_css_link(driver, css_link):415 script_to_add_css = """function injectCSS(css) {416 var head_tag=document.getElementsByTagName("head")[0];417 var link_tag=document.createElement("link");418 link_tag.rel="stylesheet";419 link_tag.type="text/css";420 link_tag.href=css;421 link_tag.crossorigin="anonymous";422 head_tag.appendChild(link_tag);423 }424 injectCSS("%s");"""425 css_link = escape_quotes_if_needed(css_link)426 driver.execute_script(script_to_add_css % css_link)427def add_js_link(driver, js_link):428 script_to_add_js = """function injectJS(link) {429 var body_tag=document.getElementsByTagName("body")[0];430 var script_tag=document.createElement("script");431 script_tag.src=link;432 script_tag.type="text/javascript";433 script_tag.crossorigin="anonymous";434 script_tag.defer;435 script_tag.onload=function() { null };436 body_tag.appendChild(script_tag);437 }438 injectJS("%s");"""439 js_link = escape_quotes_if_needed(js_link)440 driver.execute_script(script_to_add_js % js_link)441def add_css_style(driver, css_style):442 add_css_style_script = """function injectStyle(css) {443 var head_tag=document.getElementsByTagName("head")[0];444 var style_tag=document.createElement("style");445 style_tag.type="text/css";446 style_tag.appendChild(document.createTextNode(css));447 head_tag.appendChild(style_tag);448 }449 injectStyle("%s");"""450 css_style = css_style.replace("\n", "")451 css_style = escape_quotes_if_needed(css_style)452 driver.execute_script(add_css_style_script % css_style)453def add_js_code_from_link(driver, js_link):454 if js_link.startswith("//"):455 js_link = "http:" + js_link456 js_code = requests.get(js_link).text457 add_js_code_script = (458 """var body_tag=document.getElementsByTagName('body').item(0);"""459 """var script_tag=document.createElement("script");"""460 """script_tag.type="text/javascript";"""461 """script_tag.onload=function() { null };"""462 """script_tag.appendChild(document.createTextNode("%s"));"""463 """body_tag.appendChild(script_tag);"""464 )465 js_code = js_code.replace("\n", " ")466 js_code = escape_quotes_if_needed(js_code)467 driver.execute_script(add_js_code_script % js_code)468def add_js_code(driver, js_code):469 add_js_code_script = (470 """var body_tag=document.getElementsByTagName('body').item(0);"""471 """var script_tag=document.createElement("script");"""472 """script_tag.type="text/javascript";"""473 """script_tag.onload=function() { null };"""474 """script_tag.appendChild(document.createTextNode("%s"));"""475 """body_tag.appendChild(script_tag);"""476 )477 js_code = js_code.replace("\n", " ")478 js_code = escape_quotes_if_needed(js_code)479 driver.execute_script(add_js_code_script % js_code)480def add_meta_tag(driver, http_equiv=None, content=None):481 if http_equiv is None:482 http_equiv = "Content-Security-Policy"483 if content is None:484 content = (485 "default-src *; style-src 'self' 'unsafe-inline'; "486 "script-src: 'self' 'unsafe-inline' 'unsafe-eval'"487 )488 script_to_add_meta = """function injectMeta() {489 var meta_tag=document.createElement('meta');490 meta_tag.httpEquiv="%s";491 meta_tag.content="%s";492 document.getElementsByTagName('head')[0].appendChild(meta_tag);493 }494 injectMeta();""" % (495 http_equiv,496 content,497 )498 driver.execute_script(script_to_add_meta)499def is_jquery_confirm_activated(driver):500 try:501 driver.execute_script("jconfirm") # Fails if jq_confirm is not defined502 return True503 except Exception:504 return False505def activate_jquery_confirm(driver):506 jquery_js = constants.JQuery.MIN_JS507 jq_confirm_css = constants.JqueryConfirm.MIN_CSS508 jq_confirm_js = constants.JqueryConfirm.MIN_JS509 if not is_jquery_activated(driver):510 add_js_link(driver, jquery_js)511 wait_for_jquery_active(driver, timeout=1.2)512 add_css_link(driver, jq_confirm_css)513 add_js_link(driver, jq_confirm_js)514 for x in range(int(settings.MINI_TIMEOUT * 10.0)):515 # jQuery-Confirm needs a small amount of time to load & activate.516 try:517 driver.execute_script("jconfirm")518 wait_for_ready_state_complete(driver)519 wait_for_angularjs(driver)520 return521 except Exception:522 time.sleep(0.1)523def activate_html_inspector(driver):524 jquery_js = constants.JQuery.MIN_JS525 html_inspector_js = constants.HtmlInspector.MIN_JS526 if is_html_inspector_activated(driver):527 return528 if not is_jquery_activated(driver):529 add_js_link(driver, jquery_js)530 wait_for_jquery_active(driver, timeout=1.2)531 wait_for_ready_state_complete(driver)532 wait_for_angularjs(driver)533 add_js_link(driver, html_inspector_js)534 wait_for_ready_state_complete(driver)535 wait_for_angularjs(driver)536 for x in range(int(settings.MINI_TIMEOUT * 10.0)):537 # HTML-Inspector needs a small amount of time to load & activate.538 try:539 driver.execute_script("HTMLInspector")540 wait_for_ready_state_complete(driver)541 wait_for_angularjs(driver)542 return543 except Exception:544 time.sleep(0.1)545 wait_for_ready_state_complete(driver)546 wait_for_angularjs(driver)547def activate_messenger(driver):548 from seleniumbase.core import style_sheet549 jquery_js = constants.JQuery.MIN_JS550 messenger_css = constants.Messenger.MIN_CSS551 messenger_js = constants.Messenger.MIN_JS552 msgr_theme_flat_js = constants.Messenger.THEME_FLAT_JS553 msgr_theme_future_js = constants.Messenger.THEME_FUTURE_JS554 msgr_theme_flat_css = constants.Messenger.THEME_FLAT_CSS555 msgr_theme_future_css = constants.Messenger.THEME_FUTURE_CSS556 msgr_theme_block_css = constants.Messenger.THEME_BLOCK_CSS557 msgr_theme_air_css = constants.Messenger.THEME_AIR_CSS558 msgr_theme_ice_css = constants.Messenger.THEME_ICE_CSS559 spinner_css = constants.Messenger.SPINNER_CSS560 underscore_js = constants.Underscore.MIN_JS561 msg_style = (562 "Messenger.options = {'maxMessages': 8, "563 "extraClasses: 'messenger-fixed "564 "messenger-on-bottom messenger-on-right', "565 "theme: 'flat'}"566 )567 if not is_jquery_activated(driver):568 add_js_link(driver, jquery_js)569 wait_for_jquery_active(driver, timeout=0.9)570 add_css_link(driver, messenger_css)571 add_css_link(driver, msgr_theme_flat_css)572 add_css_link(driver, msgr_theme_future_css)573 add_css_link(driver, msgr_theme_block_css)574 add_css_link(driver, msgr_theme_air_css)575 add_css_link(driver, msgr_theme_ice_css)576 add_js_link(driver, underscore_js)577 add_css_link(driver, spinner_css)578 add_js_link(driver, messenger_js)579 add_css_style(driver, style_sheet.messenger_style)580 for x in range(int(settings.MINI_TIMEOUT * 10.0)):581 # Messenger needs a small amount of time to load & activate.582 try:583 result = driver.execute_script(584 """ if (typeof Messenger === 'undefined') { return "U"; } """585 )586 if result == "U":587 time.sleep(0.01)588 continue589 else:590 break591 except Exception:592 time.sleep(0.01)593 try:594 driver.execute_script(msg_style)595 add_js_link(driver, msgr_theme_flat_js)596 add_js_link(driver, msgr_theme_future_js)597 wait_for_ready_state_complete(driver)598 wait_for_angularjs(driver)599 return600 except Exception:601 time.sleep(0.1)602def set_messenger_theme(603 driver, theme="default", location="default", max_messages="default"604):605 if theme == "default":606 theme = "flat"607 if location == "default":608 location = "bottom_right"609 if hasattr(sb_config, "mobile_emulator") and sb_config.mobile_emulator:610 location = "top_center"611 if max_messages == "default":612 max_messages = "8"613 valid_themes = ["flat", "future", "block", "air", "ice"]614 if theme not in valid_themes:615 raise Exception("Theme: %s is not in %s!" % (theme, valid_themes))616 valid_locations = [617 "top_left",618 "top_center",619 "top_right",620 "bottom_left",621 "bottom_center",622 "bottom_right",623 ]624 if location not in valid_locations:625 raise Exception(626 "Location: %s is not in %s!" % (location, valid_locations)627 )628 if location == "top_left":629 messenger_location = "messenger-on-top messenger-on-left"630 elif location == "top_center":631 messenger_location = "messenger-on-top"632 elif location == "top_right":633 messenger_location = "messenger-on-top messenger-on-right"634 elif location == "bottom_left":635 messenger_location = "messenger-on-bottom messenger-on-left"636 elif location == "bottom_center":637 messenger_location = "messenger-on-bottom"638 elif location == "bottom_right":639 messenger_location = "messenger-on-bottom messenger-on-right"640 msg_style = (641 "Messenger.options = {'maxMessages': %s, "642 "extraClasses: 'messenger-fixed %s', theme: '%s'}"643 % (max_messages, messenger_location, theme)644 )645 try:646 driver.execute_script(msg_style)647 except Exception:648 activate_messenger(driver)649 driver.execute_script(msg_style)650 time.sleep(0.1)651def post_message(driver, message, msg_dur, style="info"):652 """A helper method to post a message on the screen with Messenger.653 (Should only be called from post_message() in base_case.py)"""654 if not msg_dur:655 msg_dur = settings.DEFAULT_MESSAGE_DURATION656 msg_dur = float(msg_dur)657 message = re.escape(message)658 message = escape_quotes_if_needed(message)659 messenger_script = (660 """Messenger().post({message: "%s", type: "%s", """661 """hideAfter: %s, hideOnNavigate: true});"""662 % (message, style, msg_dur)663 )664 try:665 driver.execute_script(messenger_script)666 except Exception:667 activate_messenger(driver)668 set_messenger_theme(driver)669 try:670 driver.execute_script(messenger_script)671 except Exception:672 time.sleep(0.2)673 activate_messenger(driver)674 time.sleep(0.2)675 set_messenger_theme(driver)676 time.sleep(0.5)677 driver.execute_script(messenger_script)678def post_messenger_success_message(driver, message, msg_dur):679 if not msg_dur:680 msg_dur = settings.DEFAULT_MESSAGE_DURATION681 msg_dur = float(msg_dur)682 try:683 theme = "flat"684 location = "bottom_right"685 if hasattr(sb_config, "mobile_emulator") and sb_config.mobile_emulator:686 location = "top_center"687 set_messenger_theme(driver, theme=theme, location=location)688 post_message(driver, message, msg_dur, style="success")689 time.sleep(msg_dur + 0.07)690 except Exception:691 pass692def post_messenger_error_message(driver, message, msg_dur):693 if not msg_dur:694 msg_dur = settings.DEFAULT_MESSAGE_DURATION695 msg_dur = float(msg_dur)696 try:697 set_messenger_theme(driver, theme="block", location="top_center")698 post_message(driver, message, msg_dur, style="error")699 time.sleep(msg_dur + 0.07)700 except Exception:701 pass702def highlight_with_js_2(driver, message, selector, o_bs, msg_dur):703 try:704 # This closes any pop-up alerts705 driver.execute_script("")706 except Exception:707 pass708 if selector == "html":709 selector = "body"710 selector_no_spaces = selector.replace(" ", "")711 early_exit = False712 if '[style=\\"' in selector_no_spaces:713 if 'box\\-shadow:' in selector:714 early_exit = True # Changing the box-shadow changes the selector715 elif '[style=\\"' in selector:716 selector = selector.replace('[style=\\"', '[style\\*=\\"')717 else:718 early_exit = True # Changing the box-shadow changes the selector719 if early_exit:720 try:721 activate_jquery(driver)722 post_messenger_success_message(driver, message, msg_dur)723 except Exception:724 pass725 return726 script = (727 """document.querySelector('%s').style.boxShadow =728 '0px 0px 6px 6px rgba(128, 128, 128, 0.5)';"""729 % selector730 )731 try:732 driver.execute_script(script)733 except Exception:734 return735 time.sleep(0.0181)736 script = (737 """document.querySelector('%s').style.boxShadow =738 '0px 0px 6px 6px rgba(205, 30, 0, 1)';"""739 % selector740 )741 try:742 driver.execute_script(script)743 except Exception:744 return745 time.sleep(0.0181)746 script = (747 """document.querySelector('%s').style.boxShadow =748 '0px 0px 6px 6px rgba(128, 0, 128, 1)';"""749 % selector750 )751 try:752 driver.execute_script(script)753 except Exception:754 return755 time.sleep(0.0181)756 script = (757 """document.querySelector('%s').style.boxShadow =758 '0px 0px 6px 6px rgba(50, 50, 128, 1)';"""759 % selector760 )761 try:762 driver.execute_script(script)763 except Exception:764 return765 time.sleep(0.0181)766 script = (767 """document.querySelector('%s').style.boxShadow =768 '0px 0px 6px 6px rgba(50, 205, 50, 1)';"""769 % selector770 )771 try:772 driver.execute_script(script)773 except Exception:774 return775 time.sleep(0.0181)776 try:777 activate_jquery(driver)778 post_messenger_success_message(driver, message, msg_dur)779 except Exception:780 pass781 script = """document.querySelector('%s').style.boxShadow = '%s';""" % (782 selector,783 o_bs,784 )785 try:786 driver.execute_script(script)787 except Exception:788 return789def highlight_with_jquery_2(driver, message, selector, o_bs, msg_dur):790 if selector == "html":791 selector = "body"792 selector_no_spaces = selector.replace(" ", "")793 early_exit = False794 if '[style=\\"' in selector_no_spaces:795 if 'box\\-shadow:' in selector:796 early_exit = True # Changing the box-shadow changes the selector797 elif '[style=\\"' in selector:798 selector = selector.replace('[style=\\"', '[style\\*=\\"')799 else:800 early_exit = True # Changing the box-shadow changes the selector801 if early_exit:802 try:803 activate_jquery(driver)804 post_messenger_success_message(driver, message, msg_dur)805 except Exception:806 pass807 return808 script = (809 """jQuery('%s').css('box-shadow',810 '0px 0px 6px 6px rgba(128, 128, 128, 0.5)');"""811 % selector812 )813 try:814 safe_execute_script(driver, script)815 except Exception:816 return817 time.sleep(0.0181)818 script = (819 """jQuery('%s').css('box-shadow',820 '0px 0px 6px 6px rgba(205, 30, 0, 1)');"""821 % selector822 )823 try:824 driver.execute_script(script)825 except Exception:826 return827 time.sleep(0.0181)828 script = (829 """jQuery('%s').css('box-shadow',830 '0px 0px 6px 6px rgba(128, 0, 128, 1)');"""831 % selector832 )833 try:834 driver.execute_script(script)835 except Exception:836 return837 time.sleep(0.0181)838 script = (839 """jQuery('%s').css('box-shadow',840 '0px 0px 6px 6px rgba(50, 50, 200, 1)');"""841 % selector842 )843 try:844 driver.execute_script(script)845 except Exception:846 return847 time.sleep(0.0181)848 script = (849 """jQuery('%s').css('box-shadow',850 '0px 0px 6px 6px rgba(50, 205, 50, 1)');"""851 % selector852 )853 try:854 driver.execute_script(script)855 except Exception:856 return857 time.sleep(0.0181)858 try:859 activate_jquery(driver)860 post_messenger_success_message(driver, message, msg_dur)861 except Exception:862 pass863 script = """jQuery('%s').css('box-shadow', '%s');""" % (selector, o_bs)864 try:865 driver.execute_script(script)866 except Exception:867 return868def get_scroll_distance_to_element(driver, element):869 try:870 scroll_position = driver.execute_script("return window.scrollY;")871 element_location = None872 element_location = element.location["y"]873 element_location = element_location - 130...
__init__.py
Source:__init__.py
...8 '''Unable to load jQuery on "%s" due to a possible violation '''9 '''of the website's Content Security Policy directive. '''10 '''To override this policy, add "--disable-csp" on the '''11 '''command-line when running your tests.''' % driver.current_url)12def activate_jquery(driver):13 """ If "jQuery is not defined", use this method to activate it for use.14 This happens because jQuery is not always defined on web sites. """15 try:16 # Let's first find out if jQuery is already defined.17 driver.execute_script("jQuery('html')")18 # Since that command worked, jQuery is defined. Let's return.19 return20 except Exception:21 # jQuery is not currently defined. Let's proceed by defining it.22 pass23 jquery_js = constants.JQuery.MIN_JS24 activate_jquery_script = (25 '''var script = document.createElement('script');'''26 '''script.src = "%s";document.getElementsByTagName('head')[0]'''27 '''.appendChild(script);''' % jquery_js)28 driver.execute_script(activate_jquery_script)29 for x in range(int(settings.MINI_TIMEOUT * 10.0)):30 # jQuery needs a small amount of time to activate.31 try:32 driver.execute_script("jQuery('html')")33 return34 except Exception:35 time.sleep(0.1)36 # Since jQuery still isn't activating, give up and raise an exception37 raise_unable_to_load_jquery_exception(driver)38class JQuery(object):39 """ JQuery class provides jQuery wrapper for Selenium WebElement.40 Example (set element's value attr through jQuery.val function):41 e = driver.find_element_by_id('id_name')42 JQuery(e).val('New name')43 """44 def __init__(self, element):45 self.driver = get_driver()46 activate_jquery(self.driver)47 self.element = element48 def __getattr__(self, name):49 def jquery_func(*args):50 jquery = 'return $(arguments[0]).%(func)s(%(args)s);' % {51 'func': name,52 'args': ','.join(['arguments[%d]' % (1 + i) for i in range(len(args))])53 }54 print(jquery)55 return self.driver.execute_script(jquery, self.element, *args)...
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!!