6.6 KiB
JS Package Manager and Code Generators
🕹️ SeleniumBase lets you load JavaScript packages from any CDN link into any website via Python.
🎨 The following SeleniumBase solutions utilize this feature:
🎦 (Demo Mode)
🚎 (Website Tours)
🎞️ (Presentation Maker)
📊 (Chart Maker / Dashboard)
🛂 (Dialog Boxes / MasterQA)
🗺️ This example is from maps_introjs_tour.py. (The --interval=1
makes the tour go automatically to the next step after 1 second.)
cd examples/tour_examples
pytest maps_introjs_tour.py --interval=1
🕹️ SeleniumBase includes powerful JS code generators for converting Python into JavaScript for using the supported JS packages. A few lines of Python in your tests might generate hundreds of lines of JavaScript.
🗺️ Here is some tour code in Python from maps_introjs_tour.py that expands into a lot of JavaScript.
self.open("https://www.google.com/maps/@42.3591234,-71.0915634,15z")
self.create_tour(theme="introjs")
self.add_tour_step("Welcome to Google Maps!", title="SeleniumBase Tours")
self.add_tour_step("Enter Location", "#searchboxinput", title="Search Box")
self.add_tour_step("See it", "#searchbox-searchbutton", alignment="bottom")
self.add_tour_step("Thanks for using Tours!", title="End of Guided Tour")
self.export_tour(filename="maps_introjs_tour.js")
self.play_tour()
self.add_js_link(js_link)
self.add_js_link("https://cdnjs.cloudflare.com/ajax/libs/intro.js/2.9.3/intro.min.js")
🕹️ If you're wondering how SeleniumBase does this, here's the full Python code from js_utils.py, which uses WebDriver's execute_script()
method for making JS calls after escaping quotes with backslashes as needed:
def add_js_link(driver, js_link):
script_to_add_js = (
"""function injectJS(link) {
var body = document.getElementsByTagName("body")[0];
var script = document.createElement("script");
script.src = link;
script.defer;
script.type="text/javascript";
script.crossorigin = "anonymous";
script.onload = function() { null };
body.appendChild(script);
}
injectJS("%s");""")
js_link = escape_quotes_if_needed(js_link)
driver.execute_script(script_to_add_js % js_link)
🕹️ Now that you've loaded JavaScript into the browser, you may also want to load some CSS to go along with it:
self.add_css_link(css_link)
🕹️ Here's code that loads the IntroJS CSS:
self.add_css_link("https://cdnjs.cloudflare.com/ajax/libs/intro.js/2.9.3/introjs.css")
🕹️ And here's the Python WebDriver code that makes this possible:
def add_css_link(driver, css_link):
script_to_add_css = (
"""function injectCSS(css) {
var head = document.getElementsByTagName("head")[0];
var link = document.createElement("link");
link.rel = "stylesheet";
link.type = "text/css";
link.href = css;
link.crossorigin = "anonymous";
head.appendChild(link);
}
injectCSS("%s");""")
css_link = escape_quotes_if_needed(css_link)
driver.execute_script(script_to_add_css % css_link)
↕️ (Example: dialog_box_tour.py) ↕️
Here's how to run that example:
cd examples/dialog_boxes
pytest test_dialog_boxes.py