Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jathanism/ded05692ac9316a9495cc72181a49a91 to your computer and use it in GitHub Desktop.
Save jathanism/ded05692ac9316a9495cc72181a49a91 to your computer and use it in GitHub Desktop.
a function to interact with select2 element using Selenium and Python (inspired by https://stackoverflow.com/a/17757761/8504344 and tested on firefox)
def select_option_for_select2(driver, id, text=None):
element = driver.find_element(By.XPATH, '//*[@id="{}"]/following-sibling::*[1]'.format(id))
element.click()
if text:
element = driver.find_element(By.CSS_SELECTOR, "input[type=search]")
element.send_keys(text)
try:
element.send_keys(Keys.ENTER)
except ElementNotInteractableException as e:
actions = ActionChains(driver)
a = actions.move_to_element_with_offset(element, 50, 30)
a.send_keys(Keys.ENTER)
a.perform()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment