Skip to content

Instantly share code, notes, and snippets.

@Alireza2n
Last active October 22, 2021 17:49
Show Gist options
  • Save Alireza2n/73dbdfd2ea1b87f2a034b7c76e47360e to your computer and use it in GitHub Desktop.
Save Alireza2n/73dbdfd2ea1b87f2a034b7c76e47360e 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