-
-
Save rafaelugolini/d2067a8c8c54026ac029 to your computer and use it in GitHub Desktop.
Class helper for Select2 controls with Selenium Webdriver
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from selenium.webdriver import ActionChains | |
from selenium.webdriver.common.by import By | |
from selenium.webdriver.support.ui import WebDriverWait | |
from selenium.webdriver.support import expected_conditions as EC | |
class Select2(object): | |
def __init__(self, element): | |
self.browser = element.parent | |
self.replaced_element = element | |
self.element = self.browser.find_element_by_id( | |
's2id_{0}'.format(element.get_attribute('id'))) | |
def click(self, element=None): | |
if element is None: | |
element = self.element | |
click_element = ActionChains(self.browser)\ | |
.click_and_hold(element)\ | |
.release(element) | |
click_element.perform() | |
def open(self): | |
if not self.is_open: | |
self.click() | |
WebDriverWait(self.browser, 5).until( | |
EC.visibility_of_element_located((By.XPATH, '//div[@id="select2-drop"]'))) | |
def close(self): | |
if self.is_open: | |
self.click() | |
def select(self, name): | |
self.open() | |
item_divs = self.dropdown.find_elements_by_css_selector( | |
'ul.select2-results li div.select2-result-label') | |
for field in item_divs: | |
if field.text == name: | |
self.click(field) | |
return True | |
return False | |
@property | |
def is_open(self): | |
try: | |
self.element.find_element_by_xpath('//div[@id="select2-drop"]') | |
return True | |
except: | |
return False | |
@property | |
def dropdown(self): | |
return self.element.find_element_by_xpath('//div[@id="select2-drop"]') | |
@property | |
def items(self): | |
self.open() | |
item_divs = self.dropdown.find_elements_by_css_selector( | |
'ul.select2-results li div.select2-result-label') | |
return [div for div in item_divs] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment