Skip to content

Instantly share code, notes, and snippets.

@cwurld
Created July 7, 2020 17:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cwurld/192e4e7c2282909304d4704803fb9e41 to your computer and use it in GitHub Desktop.
Save cwurld/192e4e7c2282909304d4704803fb9e41 to your computer and use it in GitHub Desktop.
Code to manipulate a Select2 widget from Selenium as if it were a normal Select
from collections import namedtuple
# Javascript scripts -----------------------------------------------------------------------------------------------
SELECT_BY_VALUE = \
'''
$(arguments[0]).val(arguments[1]);
$(arguments[0]).trigger('change');
'''
GET_OPTIONS = \
'''
var myOpts = document.getElementById(arguments[0]).options;
return myOpts;
'''
GET_SELECTIONS = \
'''
return $(arguments[0]).select2('data');
'''
# End Javascript scripts -------------------------------------------------------------------------------------------
Option = namedtuple('Option', 'text')
class Select2:
"""Drop-in replacement for Selenium Select"""
def __init__(self, webdriver, select_id: str):
self.webdriver = webdriver
self.select_id = select_id
self.options = None
def get_options(self):
if not self.options:
options_elements = self.webdriver.execute_script(GET_OPTIONS, self.select_id)
self.options = {opt.text: opt.get_attribute('value') for opt in options_elements}
return self.options
def select_by_visible_text(self, text):
options = self.get_options()
value = options[text]
self.select_by_value(value)
def select_by_value(self, value):
self.webdriver.execute_script(SELECT_BY_VALUE, '#' + self.select_id, value)
@property
def first_selected_option(self):
selections = self.webdriver.execute_script(GET_SELECTIONS, '#' + self.select_id)
option = Option(selections[0]['text'])
return option
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment