我必须使用 ActionChains 类移动到元素然后单击。然后 Select2 元素将在 Firefox 和 PhantomJS 中打开。它在 Chrome 中没有这个 hack,但我需要 PhantomJS 支持。
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
#Click on the element to open the dropdown
el = driver.find_element_by_id('id_to_element')
actions = ActionChains(driver)
actions.move_to_element(el)
actions.click()
actions.perform()
#Click on the correct item within the dropdown, waiting for it to load
item_to_select = 'Some text in select'
xpath = '//div[@class="select2-result-label" and' +\
' text()[contains(.,"%s")]]' % (item_to_select)
wait = WebDriverWait(driver, 10)
elm = wait.until(
EC.element_to_be_clickable(
(
By.XPATH,
xpath
)
),
'waiting for %s to be clickable' % (xpath)
)
elm.click()