Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
434 views
in Technique[技术] by (71.8m points)

How to select multiple options from multi select list using Selenium-Python?

I am trying to select P0_ENGLISH, P1_ENGLISH, P5_ENGLISH from multiple select which has 10 options. I want to select only these 3 options.

HTML CODE:

<select multiple="" class="gwt-ListBox" style="height: 80px; width: 205px;">
    <option title="Generic_Eng" value="Generic_Eng">Generic_Eng</option>
    <option title="Generic_Hindi" value="Generic_Hindi">Generic_Hindi</option>
    <option title="P0_English" value="P0_English">P0_English</option>
    <option title="P0_Hindi" value="P0_Hindi">P0_Hindi</option>
    <option title="P1_English" value="P1_English">P1_English</option>
    <option title="P1_Hindi" value="P1_Hindi">P1_Hindi</option>
    <option title="P4_English" value="P4_English">P4_English</option>
    <option title="P4_Hindi" value="P4_Hindi">P4_Hindi</option>
    <option title="P5_English" value="P5_English">P5_English</option>
    <option title="P5_Hindi" value="P5_Hindi">P5_Hindi</option>
</select>

SELENIUM-PYTHON CODE:

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

I've tried using this code. With this code, I am able to select the first option i.e. "P0_ENGLISH". However, after selecting the first option I get an error:

selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...