How to select multiple options from multiselect element using Selenium-Python?

女生的网名这么多〃 提交于 2019-11-28 14:23:29

To select multiple options from a Multi Select element you can use ActionChains to mock Control Click as follows:

from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys

myElemA = driver.find_element_by_css_selector(".rowStyle1:nth-child(6) .gwt-ListBox option[value='P0_English']")
myElemB = driver.find_element_by_css_selector(".rowStyle1:nth-child(6) .gwt-ListBox option[value='P1_English']")
myElemC = driver.find_element_by_css_selector(".rowStyle1:nth-child(6) .gwt-ListBox option[value='P5_English']")
ActionChains(driver).key_down(Keys.CONTROL).click(myElemA).key_up(Keys.CONTROL).perform()
ActionChains(driver).key_down(Keys.CONTROL).click(myElemB).key_up(Keys.CONTROL).perform()
ActionChains(driver).key_down(Keys.CONTROL).click(myElemC).key_up(Keys.CONTROL).perform()

In the context of Selenium, a reference is stale when the reference is invalid, because the referenced element has been deleted, or outdated as the element has been detached and then attached by a client-side script. Without knowing the precise mechanics of the client script, there may be different solutions. The easiest is to attempt to reference the element again, i.e.

queues = Select(driver.find_element_by_css_selector(".rowStyle1:nth-child(6).gwtListBox"))
queues.select_by_visible_text("P0_English")
time.sleep(3)
queues = Select(driver.find_element_by_css_selector(".rowStyle1:nth-child(6).gwtListBox"))
queues.select_by_visible_text("P1_English")
time.sleep(3)
queues = Select(driver.find_element_by_css_selector(".rowStyle1:nth-child(6).gwtListBox"))
queues.select_by_visible_text("P5_English")

This assumes that the CSS selector stays the same after the selection list is reattached. There is also a possibility that the selector becomes invalid because the element has been either removed or its location has been changed. In the first case, you'd want to throw an exception and handle it appropriately and, in the second, find out what its new selector is going to be either empirically or by client-side script code analysis. More on the StaleElementReferenceException here.

The OP is to select part of items in the multi select list, but if you want to select all the items in the list then here are the options.

JavaScript:

elements = driver.find_elements_by_css_selector(".gwt-ListBox option")
driver.execute_script("arguments[0].forEach(function(ele){ele.selected=true;});",elements)

Pyhton

elements = driver.find_elements_by_css_selector(".gwt-ListBox option")
for ele in elements:
    # select the item here
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!