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